Last updated
Testing Elasticsearch Queries
Testing Elasticsearch queries involves verifying that your query DSL returns the expected documents, with the correct relevance scores, in the right order. Elasticsearch provides several APIs for query testing and debugging: the Explain API shows why a document matched (or didn't), the Profile API shows query execution details, and the Validate API checks query syntax.
Elasticsearch Testing APIs
| API | Endpoint | Purpose |
|---|---|---|
| Search | GET /index/_search | Execute query, get results |
| Explain | GET /index/_explain/id | Why did this doc match? |
| Validate | GET /index/_validate/query | Check query syntax |
| Profile | Add "profile": true to search | Query execution timing |
| Count | GET /index/_count | Count matching docs |
Query Testing with the JavaScript Client
import { Client } from '@elastic/elasticsearch';
const client = new Client({ node: 'http://localhost:9200' });
async function testQuery(index, query) {
// Execute query
const result = await client.search({
index,
body: { query, explain: true }
});
console.log(`Total hits: ${result.hits.total.value}`);
result.hits.hits.forEach(hit => {
console.log(`Score: ${hit._score} | ID: ${hit._id}`);
if (hit._explanation) {
console.log('Explanation:', JSON.stringify(hit._explanation, null, 2));
}
});
}
// Validate query syntax
async function validateQuery(index, query) {
const result = await client.indices.validateQuery({
index,
body: { query },
explain: true
});
console.log('Valid:', result.valid);
if (!result.valid) console.log('Error:', result.error);
}