代码之家  ›  专栏  ›  技术社区  ›  Hussein Salman

嵌套弹性搜索:使用嵌套查询和嵌套对象的布尔搜索

  •  0
  • Hussein Salman  · 技术社区  · 9 年前

    我正在使用Nest Elastic并使用Head插件构建布尔搜索的查询,我正在组合多个查询

    关于DB结构和弹性映射的注意事项

    1. 数据库中的每个文档都链接到特定的profileId 反过来又具有多个属性
    2. 每个文档都有多个与其关联的属性值

    在这个查询中,我试图获取所有具有特定配置文件和属性值的文档>30,记住该属性应该仅具有属性Id 2。

    SQL查询:

    选择平均*,d、 文档d内部联接attributeValue av的名称 在…上 d、 文档Id=平均文档Id 其中d.profileid=1并且av。AttributeId=2,平均值。内部值>30

    弹性查询

       { "query": {
        "bool": {
        "must": [
        {
           "term": { "Document.profileid": "1"  }
        }
        ,
        {
          "term": {"Document.lstChildren.AttributeID": "2" }
        }
        ,
        { 
          "range": { "Document.lstChildren.IntValue": { "gt": "30"} }
        }
        ,
        {
        "match_all": { }
        }
        ],
        "must_not": [ ],
        "should": [ ]
        }
        },   "from": 0, "size": 10, "sort": [ ], "facets": { }
        }
    

    问题

    结果还包含具有以下属性值的文档

    1. 属性值=3,attributeId=2(值<30)
    2. 属性值=34,但attributeId不同于2 (不正确)

    此文件不能包含在内,因为它不能满足我的需求。

    如何构建此查询?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Hussein Salman    9 年前

    解决方案是首先通过使lstChildren成为嵌套对象来更改映射。然后使用嵌套查询将确保满足指定的所有条件。下面的嵌套查询指定了两个只返回预期结果的条件,但我使用“等于”而不是“大于”来表示“IntValue”,以保持简单:

    {
      "query": {
        "nested": {
          "path": "lstChildren",
          "query": {
            "bool": {
              "must": [
                {
                  "match": {
                    "lstChildren.AttributeID":"2"
                  }
                },
                {
                  "match": {
                    "lstChildren.IntValue": "31"
                  }
                }
              ]
            }
          }
        }
      }
    }