我正在学习 Elasticsearch,所以我不确定这个查询是否正确。我已检查数据是否已索引,但没有得到任何命中。我究竟做错了什么?这难道不应该在创作者名字叫史蒂夫的汽车上大受欢迎吗?
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": {}
}
最佳答案
首先,为了搜索嵌套字段,您需要使用 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": {}
}
'
如果使用标准分析器对 car.creators.name
进行索引,则 {"term": {"creators.name": "Steve"}}
将找不到任何内容因为单词 Steve
被索引为 steve
和 term query不执行分析。因此,最好将其替换为 match query {"match": {"creators.name": "Steve"}}
.
关于java - 查询嵌套文档 Elasticsearch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15710948/