Enter your search

Authoring Elasticsearch queries in Javascript

By
Using JS’ object literal syntax to build queries

To search something in Elasticsearch, the request looks like this:

POST https://es-cluster:9200/index-name/_search

The query definition is sent as JSON in the body of the request. Here’s an example search body:

{
"query": {
"bool": {
"filter": [
{ "term": { "field1": "foo" } },
{ "term": { "field2": "bar" } }
]
}
}
}

We have found it’s quite useful to put queries together using the improved object literal syntax of more recent versions of JavaScript:

const secondThing = { term: { field2: 'bar' } };
const firstThing = { term: { field1: 'foo' } };
const filter = [ firstThing, secondThing ];
const bool = { filter };
const query = { bool };
const body = { query };
const params = {
index: 'your-index',
body
};
const result = await es.search(params);
view raw es-search.js hosted with ❤ by GitHub

This script shows how we might build the search body for the previous request.

In the script, we’re building the query line-by-line and making use of ES2015’s shorthand property names to link it all together.

I usually find I work backwards from the es.search() statement. First are the params – defining the index and options for the request. Then onto the request body, which itself unravels into its constituent parts.

This technique can be used in Node JS or modern browsers – wherever ES2015 is supported!

You May Also Like

Group 5 Created with Sketch. Group 11 Created with Sketch. CLOSE ICON Created with Sketch. icon-microphone Group 9 Created with Sketch. CLOSE ICON Created with Sketch. SEARCH ICON Created with Sketch. Group 4 Created with Sketch. Path Created with Sketch. Group 5 Created with Sketch.

undefined

Chat with GoSquared

undefined

Chat with GoSquared
Need help? Want to know how you can make the most of GoSquared? Let's chat!

undefined

Drop files here to upload