我正在学习Elasticsearch,所以不确定此查询是否正确。我已经检查了数据是否已编制索引,但没有得到任何点击。我究竟做错了什么?这不应该在创作者名字叫史蒂夫(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": {}
}

最佳答案

首先,为了搜索嵌套字段,您需要使用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/

10-10 14:44