Using TermQueries in Elastic Search
These articles are AI-generated summaries. Please check the original sources for full details.
Using TermQueries in Elastic Search
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
keywordtypes to avoid analysis during indexing and query processing. - Spring Data Elasticsearch simplifies usage: Using Spring Data like
ElasticsearchRepositoryprovides 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
textfields 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
Wildcard Search in Elasticsearch: Techniques and Java Implementation
Master wildcard queries in Elasticsearch using Java with code examples for prefix, regexp, and fuzzy searches.
Efficient POJO Mapping to/from Java Mongo DBObject using Jackson
Discover two Jackson-based libraries, MongoJack and bson4jackson, that provide efficient POJO mappings for MongoDB, improving performance and reducing boilerplate.
MapStruct Null Values Handling
Learn different ways to handle null values during object mapping with MapStruct, improving data integrity and application robustness.