Introduction to Esquery
Esquery is an expressive and powerful library used to build and run Elasticsearch queries. Simplifying the task of creating complex search functionalities, Esquery offers an array of APIs to construct queries, making it easier and efficient for developers.
Getting Started with Esquery
To begin using Esquery, install it via npm:
npm install esquery
API Examples
Below are some of the essential APIs provided by Esquery along with code snippets to demonstrate their usage:
Query Match
import { matchQuery } from 'esquery';
const query = matchQuery('title', 'Elasticsearch');
Range Query
import { rangeQuery } from 'esquery';
const query = rangeQuery('age', { gte: 30, lt: 40 });
Bool Query
import { boolQuery } from 'esquery';
const query = boolQuery({
must: [matchQuery('name', 'John')],
filter: [rangeQuery('age', { gte: 30 })]
});
Term Query
import { termQuery } from 'esquery';
const query = termQuery('status', 'active');
Wildcard Query
import { wildcardQuery } from 'esquery';
const query = wildcardQuery('title', 'elastic*');
Exists Query
import { existsQuery } from 'esquery';
const query = existsQuery('user');
Real World Example
Let’s build a functional application using Esquery to retrieve data from an Elasticsearch index based on specific conditions:
// server.js import express from 'express'; import { Client } from '@elastic/elasticsearch'; import { boolQuery, matchQuery, rangeQuery, existsQuery } from 'esquery';
const app = express(); const client = new Client({ node: 'http://localhost:9200' });
app.get('/search', async (req, res) => {
const query = boolQuery({
must: [matchQuery('name', req.query.name)],
filter: [rangeQuery('age', { gte: req.query.age }), existsQuery('email')]
});
const { body } = await client.search({
index: 'users',
body: { query }
});
res.send(body.hits.hits);
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
With this setup, you can run your Express server and fetch user data from the Elasticsearch index based on the input parameters provided in the URL query string.
Conclusion
Esquery is a versatile and powerful tool that simplifies querying Elasticsearch indexes. Whether you are constructing simple match queries or complex boolean queries, Esquery’s comprehensive API suite has got you covered.
To explore Esquery further, check out the official documentation.
Hash: c22cb824e27be81f5d2b9dbed78070938faf4b9e60fa9cc5a33af79b17b5e7fa