AWS Elasticsearch多词与部分字符串混合搜索实现求助
Got it, let's tackle your problem: you need a unified query approach that handles both partial string matches (like searching "Spi" to find "Spider Man") and multi-term partial matches (like "Spider M" to target the same document). Here are two practical solutions that fit your exact requirements:
Solution 1: Bool Query + Wildcard Clauses
This method uses a bool query with must clauses to enforce that all partial match conditions are met. Each term in your search gets its own wildcard check, mimicking the "AND" logic from your original match query while adding partial string support.
Single Partial Term ("Spi")
{ "query": { "bool": { "must": [ { "wildcard": { "TitleKeywords": "*Spi*" } } ] } } }
Multi Partial Terms ("Spider M")
{ "query": { "bool": { "must": [ { "wildcard": { "TitleKeywords": "*Spider*" } }, { "wildcard": { "TitleKeywords": "*M*" } } ] } } }
Solution 2: Query String with Wildcards & AND Logic
If you prefer a more concise syntax, use query_string to wrap each term in wildcards and enforce "AND" matching. This works great for dynamically building queries with variable numbers of search terms.
Single Partial Term ("Spi")
{ "query": { "query_string": { "default_field": "TitleKeywords", "query": "*Spi*" } } }
Multi Partial Terms ("Spider M")
{ "query": { "query_string": { "default_field": "TitleKeywords", "query": "*Spider* AND *M*", "default_operator": "AND" } } }
Key Tips for Better Results
- Field Type Check: If your
TitleKeywordsis atextfield (which splits content into individual words), use itskeywordsubfield (e.g.,TitleKeywords.keyword) for wildcard searches. This ensures you match against the full original string instead of split tokens, avoiding unexpected misses. - Performance Optimization: Wildcard queries starting with
*(like*Spi*) can be slow on large datasets because Elasticsearch can’t use its inverted index efficiently. For better speed, set up an ngram tokenizer on your field. This pre-splits text into small character chunks (e.g., 2-5 characters), letting you use fastmatchqueries while still supporting partial matches.
内容的提问来源于stack exchange,提问作者Ankit Uniyal

