【问题标题】:Elasticsearch conditional query for nested array嵌套数组的 Elasticsearch 条件查询
【发布时间】:2019-12-28 06:43:06
【问题描述】:

使用以下文档,我正在尝试执行 Elasticsearch 关键字查询,有条件地将字段数据排除在搜索范围之外。这可能吗?

{
  "Name":"doc1",
  "UserData":[
      {
         "EnteredBy":"Eric",
         "Description":"Desc entered by Eric, abc"
      },
      {
         "EnteredBy":"Alex",
         "Description":"Desc entered by Alex, def"
      }
   ]
}

我需要的 Elasticsearch 查询将允许我搜索整个文档,但它应该从搜索中排除 EnteredBy 与指定用户不匹配的 UserData 项目。

以下查询将返回结果:

User:Eric doc1
User:Eric abc
User:Alex doc1
User:Fred doc1

以下查询不会返回结果:

User:Eric def
User:Fred def

到目前为止,我所做的一切都是根据适用于指定用户的 UserData 节点的存在来过滤内容。我想不出一种方法来指定应该搜索一个字段,只有当 EnteredBy 字段匹配时。

如果可以解决问题,我可以重新构建文档。

编辑 1

索引..

PUT index1
{
  "settings": {
    "number_of_shards": 2,
    "number_of_replicas": 0
  },
  "mappings": {
    "properties" : {
      "UserData" : {
        "type":"nested"
      },
      "Name": {
        "type":"text"
      }
    }
  }
}

编辑 2

下面的查询提供了我需要的结果,除了子实体,我必须在特定字段中搜索。如果我将嵌套搜索的第二个条件更改为 query_string 搜索,则它不再使用 EnteredBy 条件。

GET index1/_search
{
 "query": {
      "bool": { 
        "should": [
        {
          "nested": 
          {
               "path": "UserData",
               "query": {
                  "bool": {
                    "must": [{
                      "match": {
                        "UserData.EnteredBy": "Eric"
                      }},
                      {
                        "match": {
                        "UserData.Description": "def"
                      }
                    }]

                  }
                }
          }
        },
        { 
          "query_string": 
          { 
            "query": "doc1x" 
          }

        }
      ]
     }
  }
}

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    此查询似乎正在运行。我想我已经回答了我自己的问题。

    GET index1/_search
    {
     "query": {
          "bool": { 
            "should": [
            {
              "nested": 
              {
                   "path": "UserData",
                   "query": {
                      "bool": {
                        "must": [{
                          "match": {
                            "UserData.EnteredBy": "Eric"
                          }},
                          {
                            "query_string": {
                            "query": "def"
                          }
                        }]
    
                      }
                    }
              }
            },
            { 
              "query_string": 
              { 
                "query": "doc1" 
              }
    
            }
          ]
         }
      }
    }
    

    【讨论】:

    • 如果您找到了解决问题的方法,请考虑接受您自己的答案 :)
    • 谢谢@KevinQuinzel,在 2 天的 SF 等待期后会做的。
    猜你喜欢
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多