Skip to main content

On This Page

Using TermQueries in Elastic Search

2 min read
Share

These articles are AI-generated summaries. Please check the original sources for full details.

TermQuery is a core Elasticsearch building block executing exact matches against fields without analysis, optimized for structured data like keywords, booleans, and identifiers. Elasticsearch’s power lies in its ability to quickly sift through large datasets, and TermQueries are fundamental to achieving this efficiency when dealing with precise search criteria.

Why This Matters

Elasticsearch aims to provide flexible text search, however, relying solely on analyzed text fields can lead to imprecise results and performance bottlenecks when needing exact matches. TermQueries address this by bypassing analysis, offering a faster, more predictable way to filter data – crucial for applications where data integrity and speed are paramount, avoiding costly full-text scans when analytical precision is required.

Key Insights

  • Boolean filters outperform full-text search: Term queries are significantly faster than typical text searches, as they work directly on the indexed terms.
  • Keyword fields are essential: Term queries require fields mapped as keyword types to avoid analysis during indexing and query processing.
  • Spring Data Elasticsearch simplifies usage: Using Spring Data like ElasticsearchRepository provides a higher-level abstraction over the Elasticsearch DSL, streamlining development.

Working Example

@SpringBootTest
@ContextConfiguration(classes = ElasticsearchConfiguration.class)
public class ElasticSearchTermsQueriesManualTest {
@Autowired
private ElasticsearchClient elasticsearchLowLevelClient;
@Test
void givenAdminRoleAndActiveStatusFilter_whenSearch_thenReturnsOnlyActiveAdmins() throws Exception {
Query roleQuery = TermQuery.of(t -> t.field("role.keyword").value("admin"))._toQuery();
Query activeQuery = TermQuery.of(t -> t.field("is_active").value(true))._toQuery();
Query boolQuery = BoolQuery.of(b -> b.filter(roleQuery).filter(activeQuery))._toQuery();
SearchRequest request = SearchRequest.of(s -> s.index("users").query(boolQuery));
SearchResponse<Map> response = elasticsearchLowLevelClient.search(request, Map.class);
assertThat(response.hits().hits())
.hasSize(1)
.first()
.extracting(Hit::source)
.satisfies(source -> {
assertThat(source)
.isNotNull()
.values()
.containsExactly("1", "Alice", "admin", true);
});
}
}

Practical Applications

  • User Authentication: Filtering active users with specific roles before allowing access to sensitive features.
  • Pitfall: Using analyzed text fields for term queries – resulting in unexpected behavior due to tokenization and stemming.

References:

Continue reading

Next article

Wallet-as-a-Service: The Missing Layer in Modern Web3 Infrastructure

Related Content