VOOZH about

URL: https://www.javacodegeeks.com/wildcard-search-in-elasticsearch.html

⇱ Wildcard Search in Elasticsearch - Java Code Geeks


Wildcard search is a flexible feature in Elasticsearch that allows us to match text patterns rather than exact values. It is well-suited for scenarios where users search with partial input, unknown suffixes or prefixes, or loosely structured identifiers. In this article, we explore how wildcard searches work in Elasticsearch and how to implement them effectively using Java.

1. Understanding Wildcard Search in Elasticsearch

Wildcard search allows us to match terms using special characters such as * and ?. The asterisk (*) matches zero or more characters, while the question mark (?) matches exactly one character. Internally, wildcard queries operate on terms, not analyzed text, which means they are best suited for keyword fields or non-analyzed values.

Tip
Because wildcard queries can be expensive, especially when they begin with *, they should be used thoughtfully and often combined with filters or constraints to reduce performance impact.

1.1 Wildcard Query Syntax and Behaviour

Elasticsearch provides the wildcard query as part of its Query DSL. This query matches documents where a field’s value matches a specified wildcard pattern. Wildcard queries are case-sensitive unless the field is normalized or lowercased at index time.

Wildcard patterns such as admin* can be used to match values that start with admin, while error? matches terms like error1 or errorA, and *service* matches values that contain the word service. These queries are most effective when applied to fields mapped as keyword or to custom subfields such as field.keyword, where values are not analysed.

2. Index Mapping and Sample Data

Wildcard queries operate on exact terms, so fields used in wildcard searches must be mapped as keywords. We define a simple domain model that aligns with the Elasticsearch index mapping.

@Document(indexName = "services")
public class ServiceDocument {

 @Id
 private String id;

 @Field(type = FieldType.Keyword)
 private String serviceName;

 @Field(type = FieldType.Keyword)
 private String environment;

 public ServiceDocument() {
 }

 public ServiceDocument(String id, String serviceName, String environment) {
 this.id = id;
 this.serviceName = serviceName;
 this.environment = environment;
 }

 public String getId() {
 return id;
 }

 public void setId(String id) {
 this.id = id;
 }

 public String getServiceName() {
 return serviceName;
 }

 public void setServiceName(String serviceName) {
 this.serviceName = serviceName;
 }

 public String getEnvironment() {
 return environment;
 }

 public void setEnvironment(String environment) {
 this.environment = environment;
 }
 
}

Indexing Sample Data

Before running wildcard queries, we need data in the index. For this article, sample data is loaded using the DataInitializer class below.

@Service
public class DataInitializer {

 private final ElasticsearchOperations operations;

 public DataInitializer(ElasticsearchOperations operations) {
 this.operations = operations;
 }

 @PostConstruct
 public void init() {
 operations.save(new ServiceDocument(null, "auth-service", "production"));
 operations.save(new ServiceDocument(null, "auth-gateway", "staging"));
 operations.save(new ServiceDocument(null, "payment-service", "production"));
 operations.save(new ServiceDocument(null, "order-service", "production"));
 }
}

3. Basic Wildcard Search Using Spring Data Elasticsearch

3.1 Performing a Basic Wildcard Prefix Search

We now perform our first wildcard search using the Elasticsearch client. This example matches all services whose names start with a specific prefix.

Prefix Wildcard Search (auth*)

 public void searchByPrefix() {

 try {
 SearchResponse<ServiceDocument> response = elasticsearchClient.search(s -> s
 .index("services")
 .query(q -> q
 .wildcard(w -> w
 .field("serviceName")
 .value("auth*"))), ServiceDocument.class);

 if (response.hits().hits().isEmpty()) {
 log.warn("No documents found for wildcard auth*");
 }

 for (Hit<ServiceDocument> hit : response.hits().hits()) {
 ServiceDocument doc = hit.source();
 log.info("{} | {}", doc.getServiceName(), doc.getEnvironment());
 }

 } catch (Exception e) {
 log.error("Wildcard search failed", e);
 }
 }

This code constructs a wildcard query that matches documents whose serviceName begins with auth. The search response is mapped directly to ServiceDocument, and the results are logged to the console.

3.2 Performing a Suffix Wildcard Search

Suffix wildcard searches allow us to match values that end with a known pattern. This is useful for identifying groups of services or identifiers that share a common suffix.

Suffix Wildcard Search (*service)

 public void searchBySuffix() throws Exception {

 SearchResponse<ServiceDocument> response
 = elasticsearchClient.search(s -> s
 .index("services")
 .query(q -> q
 .wildcard(w -> w
 .field("serviceName")
 .value("*service"))), ServiceDocument.class);

 response.hits().hits().forEach(hit -> {
 log.info(hit.source().getServiceName());
 });
 }

This query matches all service names ending with service. Because the wildcard appears at the beginning of the pattern, this query is more expensive and should be used carefully in production environments.

3.3 Combining Wildcard Search with Filters

In typical application scenarios, wildcard queries are often combined with filters to narrow down the result set and improve performance.

Wildcard Query Inside a Bool Query

 public void searchWithFilter() throws Exception {

 SearchResponse<ServiceDocument> response
 = elasticsearchClient.search(s -> s
 .index("services")
 .query(q -> q
 .bool(b -> b
 .must(m -> m
 .wildcard(w -> w
 .field("serviceName")
 .value("*service")))
 .filter(f -> f
 .term(t -> t
 .field("environment")
 .value("production"))))), ServiceDocument.class);

 response.hits().hits().forEach(hit -> {
 ServiceDocument doc = hit.source();
 log.info("{} | {}", doc.getServiceName(), doc.getEnvironment());
 });
 }

This method performs a wildcard search on the services index, matching documents whose serviceName ends with service, and applies a term filter on the environment field to return only production services. The filter limits the result set without affecting scoring, improving query efficiency.

3.4 Case-Insensitive Wildcard Search

Elasticsearch supports case-insensitive wildcard queries, which is useful when input casing cannot be controlled.

Case-Insensitive Wildcard Query

 public void caseInsensitiveSearch() throws Exception {

 SearchResponse<ServiceDocument> response
 = elasticsearchClient.search(s -> s
 .index("services")
 .query(q -> q
 .wildcard(w -> w
 .field("serviceName")
 .value("AUTH*")
 .caseInsensitive(true))), ServiceDocument.class);

 response.hits().hits().forEach(hit -> {
 log.info(hit.source().getServiceName());
 });
 }

This query matches service names regardless of letter case, removing the need for custom normalizers or lowercasing logic at index time.

Verifying Execution with a CommandLineRunner

To confirm all examples run successfully, we invoke them at startup.

@Component
public class Runner implements CommandLineRunner {

 private final WildcardSearchService service;

 public Runner(WildcardSearchService service) {
 this.service = service;
 }

 @Override
 public void run(String... args) throws Exception {
 service.searchByPrefix();
 service.searchBySuffix();
 service.searchWithFilter();
 service.caseInsensitiveSearch();
 }
}

4. Performance Considerations

Wildcard queries can be costly, especially when the pattern begins with *, so they should be used carefully. To reduce performance impact, prefer suffix wildcards (prefix*) over leading wildcards (*suffix), run wildcard queries on keyword fields or normalized subfields, and combine them with filters to narrow the result set.

It is also advisable to limit wildcard searches to small, well-defined indices, and for high-volume text search scenarios, consider alternatives such as edge n-grams or the prefix query.

5. Conclusion

In this article, we explored how to perform wildcard searches in Elasticsearch using Java, covering basic wildcard queries, boolean filter combinations, and case-insensitive matching. When used carefully, wildcard queries offer flexible and expressive search capabilities while remaining performant in practical applications.

6. Download the Source Code

This article explored wildcard search in Elasticsearch using Java.

Download
You can download the full source code of this example here: java elasticsearch wildcard
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

πŸ‘ Photo of Omozegie Aziegbe
Omozegie Aziegbe
December 24th, 2025Last Updated: December 23rd, 2025
0 300 4 minutes read

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button
Close
wpDiscuz