ElasticSearch 5嵌套字段搜索问题:查询persons.id=P123报错求助
persons.id=P123 in Elasticsearch 5.5 Hey there! Let's work through this problem together. When querying fields like persons.id in Elasticsearch 5.5, the most common issues usually tie to how your data is mapped (nested vs. plain object) or how you're structuring your query. Here's a breakdown of solutions:
First, Check Your Mapping
Before diving into queries, confirm how your persons field is defined in the index mapping. Run this command to inspect it:
GET /your_index_name/_mapping
Look for the persons entry—note if it's marked as "type": "nested" or "type": "object". Also check the persons.id field: is it a text type (with a keyword subfield) or a straight keyword?
Case 1: persons is a Plain Object Type
If persons is a regular object (not nested), use a simple term query (best for exact matches like IDs):
GET /your_index_name/_search { "query": { "term": { "persons.id": "P123" } } }
If persons.id was mapped as a text type (and got split into tokens), you might need to use the keyword subfield instead:
GET /your_index_name/_search { "query": { "term": { "persons.id.keyword": "P123" } } }
Case 2: persons is a Nested Type
If persons is a nested field (common when you have arrays of objects), you must use a nested query to correctly target individual objects in the array:
GET /your_index_name/_search { "query": { "nested": { "path": "persons", "query": { "term": { "persons.id": "P123" } } } } }
Again, if persons.id is a text type, swap to persons.id.keyword inside the nested query.
Common Mistakes to Troubleshoot
- Typos/Case Sensitivity: Double-check that the field name is exactly
persons.id(ES field names are case-sensitive!). - Wrong Query Type: Using a plain term query on a nested field will return no results—Elasticsearch flattens nested objects by default, so you need the nested wrapper.
- Tokenization Issues: If
P123is being split into separate tokens (like "P" and "123"), thetermquery won't match. Using thekeywordsubfield fixes this, as it stores the exact value.
If you're still getting errors, share the exact error message and your index mapping snippet—we can narrow it down further!
内容的提问来源于stack exchange,提问作者user1187968

