Skip to content

Latest commit

 

History

History
67 lines (54 loc) · 1.47 KB

File metadata and controls

67 lines (54 loc) · 1.47 KB
endpoint search
lang javascript
es_version 9.3
client @elastic/elasticsearch@9.3.0

Elasticsearch 9.3 search endpoint (JavaScript example)

Use client.search() to find documents matching a query.

const response = await client.search({
  index: "products",
  query: { match: { category: "electronics" } },
  sort: [{ price: "asc" }],
});

console.log(`Found ${response.hits.total.value} products`);
for (const hit of response.hits.hits) {
  console.log(`  ${hit._source.name} — $${hit._source.price}`);
}

Pagination

Use from and size to paginate through results:

const page = 0;
const pageSize = 10;

const response = await client.search({
  index: "products",
  query: { match_all: {} },
  from: page * pageSize,
  size: pageSize,
  sort: [{ price: "desc" }],
});

For deep pagination beyond 10,000 results, use search_after with a point-in-time instead.

Aggregations

Use aggs to compute summary statistics alongside search results. Set size: 0 when you only need the aggregation, not the documents:

const response = await client.search({
  index: "products",
  size: 0,
  aggs: {
    by_category: {
      terms: { field: "category.keyword" },
      aggs: {
        avg_price: { avg: { field: "price" } },
      },
    },
  },
});

for (const bucket of response.aggregations.by_category.buckets) {
  console.log(`  ${bucket.key}: ${bucket.doc_count} products, avg $${bucket.avg_price.value.toFixed(2)}`);
}