Enter your search

Authoring Elasticsearch queries in Javascript

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:

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

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.