ElasticSearch 简单查询

ElasticSearch simple query

我的 ElasticSearch 中有这样的结构

{
        _index: 'index',
        _type: 'product',
        _id: '896',
        _score: 0,
        _source: {
          entity_id: '896',
          category: [
            {
              category_id: 2,
              is_virtual: 'false'
            },
            {
              category_id: 82,
              is_virtual: 'false'
            }
          ]
        }
      }

我想要return所有"producs"有“82”category_id。

{
  "query": {
    "bool": {
      "filter": {
        "terms": {
          "category.category_id": [
            82
          ]
        }
      }
    }
  }
}

这个查询给了我 0 个匹配。

正确的做法是什么?

如果您的查询没有结果,我怀疑 category 属于 type nested in your index mapping. If that's the case, that's good and you can modify your query like this to use the nested query:

{
  "query": {
    "bool": {
      "filter": {
        "nested": {
          "path": "category",
          "query": {
            "terms": {
              "category.category_id": [
                82
              ]
            }
          }
        }
      }
    }
  }
}

添加工作示例,您需要将 category 定义为嵌套字段并通过包含 nested 路径 [=16= 来修改您的搜索查询]

索引映射

{
    "mappings": {
        "properties": {
            "entity_id": {
                "type": "text"
            },
            "category": {
                "type": "nested"
            }
        }
    }
}

为您的文档编制索引

{
    "entity_id": "896",
    "category": [
        {
            "category_id": 2,
            "is_virtual": false
        },
        {
            "category_id": 82,
            "is_virtual": false
        }
    ]
}

正确的搜索查询,请注意我们使用的是不支持普通过滤器的嵌套查询(因此您的查询会出错)

{
    "query": {
        "nested": {
            "path": "category",
            "query": {
                "bool": {
                    "must": [
                        {
                            "match": {
                                "category.category_id": 82
                            }
                        }
                    ]
                }
            }
        }
    }
}

搜索结果返回索引文档

 "hits": [
            {
                "_index": "complexnested",
                "_type": "_doc",
                "_id": "1",
                "_score": 1.0,
                "_source": {
                    "entity_id": "896",
                    "category": [
                        {
                            "category_id": 2,
                            "is_virtual": false
                        },
                        {
                            "category_id": 82,
                            "is_virtual": false
                        }
                    ]
                }
            }
        ]