乐闻世界logo
搜索文章和话题

Elasticsearch how to use multi_match with wildcard

1个答案

1

In Elasticsearch, the multi_match query is a very useful feature for executing the same query across multiple fields. If you wish to use wildcards in this query, you can achieve this in various ways, but note that directly using wildcards in the multi_match query is not supported. However, you can use the query_string query to achieve similar results to multi_match while supporting wildcards. I will explain how to implement this with a specific example.

Assume we have an index containing documents about books, each with title and description fields. Now, if we want to find books where the title or description contains terms like 'comp*' (representing 'computer', 'companion', 'complex', etc.), we can use the query_string query to perform this wildcard search across multiple fields.

Example

Assume our index is named books. We can construct the following query:

json
GET /books/_search { "query": { "query_string": { "query": "(title:comp* OR description:comp*)", "fields": ["title", "description"] } } }

In this query:

  • The query_string query allows us to directly use Lucene query syntax in the query parameter, including wildcards such as *.
  • We use (title:comp* OR description:comp*) to specify that we are searching for terms starting with 'comp' in the title and description fields.
  • The fields parameter explicitly specifies the fields to search.

Notes

When using wildcards with the query_string query, exercise caution as it may lead to decreased query performance, especially when the wildcard query part involves a large number of term matches. Additionally, wildcard queries placed at the beginning of a word, such as *comp, may cause performance issues because this type of query typically scans each term in the index.

In summary, although the multi_match query itself does not directly support wildcards, by using the query_string query, you can achieve wildcard search across multiple fields while maintaining the flexibility and power of the query. In practice, it is recommended to carefully choose and optimize the query method based on the specific data and requirements.

2024年6月29日 12:07 回复

你的答案