Client Elasticsearch pour Node.js : @elastic/elasticsearch

Formateur Python en ligne pour débutants

Apprenez Python facilement sans surcharge théorique. Résolvez des tâches pratiques avec vérification automatique et écrivez du code directement dans le navigateur.

Start Course

Client Elasticsearch pour Node.js (@elastic/elasticsearch)



La bibliothèque @elastic/elasticsearch est le client HTTP officiel et haute performance pour interagir avec Elasticsearch depuis l'environnement Node.js. Elle fournit une API pratique pour effectuer toutes les opérations : de l'indexation simple de documents aux requêtes de recherche complexes et aux agrégations. La bibliothèque prend entièrement en charge toutes les versions d'Elasticsearch 7.x et 8.x, y compris le travail avec des clusters, l'authentification et la compression des données.



Installation

Pour l'installation, utilisez npm ou yarn :

npm install @elastic/elasticsearch# ouyarn add @elastic/elasticsearch


Connexion de base

Créez une instance du client en spécifiant l'adresse du serveur Elasticsearch. Pour la version 8.x, une configuration TLS et une clé API ou un nom d'utilisateur/mot de passe sont requis.

const { Client } = require('@elastic/elasticsearch');

// Connexion à un serveur local (Elasticsearch 7.x)const client = new Client({ node: 'http://localhost:9200' });

// Connexion à un serveur cloud Elastic Cloud (8.x)const cloudClient = new Client({ cloud: { id: 'my-cloud-id' }, auth: { apiKey: 'base64EncodedApiKey' }});


Opérations principales



1. Indexation (ajout) d'un document

La méthode index ajoute ou remplace un document dans l'index spécifié.

async function indexDocument() {  const result = await client.index({    index: 'articles',    id: '1',    body: {      title: 'Client Elasticsearch pour Node.js',      content: 'Description détaillée de la bibliothèque...',      tags: ['elasticsearch', 'node.js'],      published: true,      views: 150    }  });  console.log('Document indexé :', result.result);}indexDocument();


2. Recherche de documents

La méthode search effectue une recherche en texte intégral à l'aide de Query DSL.

async function searchDocuments() {  const { body } = await client.search({    index: 'articles',    body: {      query: {        bool: {          must: [            { match: { title: 'Elasticsearch' } },            { term: { published: true } }          ],          filter: [            { range: { views: { gte: 100 } } }          ]        }      }    }  });

console.log('Documents trouvés :', body.hits.total.value); body.hits.hits.forEach(hit => { console.log(`- ${hit._source.title} (pertinence : ${hit._score})`); });}searchDocuments();


3. Récupération d'un document par ID

async function getDocument() {  try {    const { body } = await client.get({      index: 'articles',      id: '1'    });    console.log('Document :', body._source);  } catch (error) {    if (error.meta.statusCode === 404) {      console.log('Document non trouvé');    } else {      console.error('Erreur :', error);    }  }}getDocument();


4. Mise à jour d'un document (partielle)

async function updateDocument() {  const { body } = await client.update({    index: 'articles',    id: '1',    body: {      doc: {        views: 151,        updated_at: new Date().toISOString()      }    }  });  console.log('Document mis à jour, version :', body._version);}updateDocument();


5. Suppression d'un document

async function deleteDocument() {  const { body } = await client.delete({    index: 'articles',    id: '1'  });  console.log('Résultat de la suppression :', body.result);}deleteDocument();


Travailler avec les agrégations

Les agrégations permettent d'obtenir des données statistiques à partir des résultats de recherche.

async function aggregateByTags() {  const { body } = await client.search({    index: 'articles',    body: {      size: 0, // ne pas retourner les documents eux-mêmes      aggs: {        popular_tags: {          terms: { field: 'tags.keywor                    

Recommendations