1

我的 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'
            }
          ]
        }
      }

我想返回所有具有“82”category_id 的“产品”。

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

这个查询给了我 0 次点击。

这样做的正确方法是什么?

4

2 回答 2

2

Adding working example, you need to define the category as nested field and modify your search query by including the nested path

Index Mapping

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

Index your document

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

Proper search query, note we are using nested query which doesn't support normal filter(so your query gives error)

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

Search result retuns indexed doc

 "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
                        }
                    ]
                }
            }
        ]
于 2020-06-04T06:18:31.643 回答
1

如果您的查询没有给您任何结果,我怀疑这category是您的索引映射中的类型nested。如果是这种情况,那很好,您可以像这样修改查询以使用nested查询

{
  "query": {
    "bool": {
      "filter": {
        "nested": {
          "path": "category",
          "query": {
            "terms": {
              "category.category_id": [
                82
              ]
            }
          }
        }
      }
    }
  }
}
于 2020-06-04T06:16:08.810 回答