Querying nested document Elasticsearch
elasticsearch, full-text-search, jakarta-ee, java
Solution
First of all, in order to search nested fields you need to use nested query:
curl -XDELETE localhost:9200/test
curl -XPUT localhost:9200/test -d '{
"settings": {
"index.number_of_shards": 1,
"index.number_of_replicas": 0
},
"mappings": {
"car": {
"properties": {
"creators" : {
"type": "nested",
"properties": {
"name": {"type":"string"}
}
}
}
}
}
}
}
'
curl -XPOST localhost:9200/test/car/1 -d '{
"creators": {
"name": "Steve"
}
}
'
curl -X POST 'http://localhost:9200/test/_refresh'
echo
curl -X GET 'http://localhost:9200/test/car/_search?pretty' -d ' {
"query": {
"nested": {
"path": "creators",
"query": {
"bool": {
"must": [{
"match": {
"creators.name": "Steve"
}
}],
"must_not": [],
"should": []
}
}
}
},
"from": 0,
"size": 50,
"sort": [],
"facets": {}
}
'
If `car.creators.name` was indexed using standard analyzer then `{"term": {"creators.name": "Steve"}}` will not find anything because word `Steve` was indexed as `steve` and the term query doesn't performs analysis. So, it might be better to replace it with the match query `{"match": {"creators.name": "Steve"}}`.
Problem
I am learning Elasticsearch so I am not sure if this query is correct. I have checked that the data is indexed, but I don't get any hits. What am I doing wrong? Shouldn't this get a hit on a car where the creator's name is steve? ``` builder .startObject() .startObject("car") .field("type", "nested") .startObject("properties") .startObject("creators") .field("type", "nested") .endObject() .endObject() .endObject() .endObject(); { "query": { "bool": { "must": [ { "term": { "car.creators.name": "Steve" } } ], "must_not": [], "should": [] } }, "from": 0, "size": 50, "sort": [], "facets": {} } ```