Elasticsearch是否支持多值AND查询?5.3版本嵌套数组查询需求
1. Does Elasticsearch support AND queries for multi-value fields?
Absolutely, but the approach depends on how your data is structured:
Simple multi-value fields (e.g., an array of strings/numbers like
tags: ["foo", "bar"]): Use aboolquery withmustclauses to enforce AND logic. For example, to find documents with both "foo" and "bar" tags, pair twotermqueries insidebool.must.Arrays of objects (like your
itemsfield): This requires special handling. By default, Elasticsearch flattens object arrays, merging fields from all objects into a single list. Without proper scoping, a query foritems.id: "1"ANDitems.range.from: <=15might accidentally match across different objects in the array. To fix this, use thenestedquery to ensure all conditions apply to the same object within the array.
2. Correct Query for Matching ID and Corresponding Range
First, ensure your items field is mapped as a nested type. If it isn’t already, you’ll need to set up or update your index mapping (note: in Elasticsearch 5.3, you can’t modify existing mappings, so you may need to reindex your data if the current mapping uses the default object type for items).
Example Nested Mapping
PUT product { "mappings": { "item": { "properties": { "userId": { "type": "keyword" }, "items": { "type": "nested", "properties": { "id": { "type": "keyword" }, "range": { "properties": { "from": { "type": "integer" }, "to": { "type": "integer" } } } } } } } } }
Query to Match a Specific ID and Its Range
Let’s say you want to find the document where userId is "123", and there’s an item with id "1" that includes the value 15 in its range. Here’s the correct query:
GET product/item/_search { "query": { "bool": { "filter": [ { "term": { "userId": "123" } }, { "nested": { "path": "items", "query": { "bool": { "must": [ { "term": { "items.id": "1" } }, { "range": { "items.range.from": { "lte": 15 } } }, { "range": { "items.range.to": { "gte": 15 } } } ] } } } } ] } } }
How This Works:
- The
nestedquery scopes inner conditions to theitemsarray, ensuring theidmatch and range checks apply to the same object in the array. - The
bool.mustinside the nested query enforces that all conditions (matching id, value >= from, value <= to) are met for that single item.
Adjust the range conditions based on your needs (e.g., looking for items where range.from < 25 or range.to > 50).
内容的提问来源于stack exchange,提问作者parth

