field - 返回一个自定义字段,其中值取决于Elasticsearch中的查询

标签 field elasticsearch

我在Elasticsearch中有一些类似的数据:

account (http://localhost:9200/myapp/account/1)
========
name
state
groups //groups is an array containing objects like so {id: 1, starred: true}
       //the id is the id of the group type

email (http://localhost:9200/myapp/email/1?parent=1)
========
email
primary //just a boolean to denote whether this email is primary or not

group
========
name
description
emailaccount的子级。

基于imotov's excellent answer,我可以对account.nameemail.email进行搜索,并返回所有account,其中搜索的前缀与上述两个字段匹配:
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "statuses": "active"
          }
        }
      ],
      "should": [
        {
          "prefix": {
            "name": "a"
          }
        },
        {
          "has_child": {
            "type": "email",
            "query": {
              "prefix": {
                "email": "a"
              }
            }
          }
        }
      ],
      "minimum_number_should_match" : 1
    }
  }
}

我现在想做的是为每个结果返回2个自定义字段:
  • 对于每个结果,返回一个名为email的字段,如果搜索符合email类型(它是account的子代),则返回该电子邮件,否则返回链接到该帐户的primary电子邮件,如果没有,则可以返回null
  • 对于每个结果,返回一个名为group的字段。该字段的值应包含加星号的group的名称,其ID存储在groups数组中。本质上:在每个group.id中找到group.starred为true的account.groups,然后根据找到的id从group.name类型返回匹配的group

  • 我一直在看script fields,但是我不确定它是否能够为每个匹配返回字段。我也不确定以上内容在ES中是否可以实现。

    有人能提供一些关于这是否可行以及如何开始的指示吗?

    最佳答案

    当前,根本没有办法访问has_childnested子句中的数据。

    唯一的解决方案是获取一些数据,在客户端上做出一些决定,然后获取更多数据。

    这是我为实现该目标所做的事情:

  • 运行上面的查询并获取数据。
  • 要处理显示匹配电子邮件或主要电子邮件(在电子邮件类型上运行):
    {"query":
        {"bool":{
           "should":{
            {
               "prefix":{
                  "email" : "the query"
               }
            },
            {
               "terms":{
                  "_parent" : ["list", "of", "account", "ids"]
              }
           }
          }
        }
      }
    }
    

  • 根据上述查询,我​​们可以获得与搜索词匹配的任何电子邮件地址。请记住,将以上查询中的字段设置为包括_parent

    然后,我们可以使用array_diff()或类似PHP之外的语言的类似函数来区分上方的父ID和原始查询。然后,这将为我们提供没有电子邮件匹配的帐户列表。然后,只需发送另一个请求即可获取这些帐户的主要电子邮件。

    对于组,发送查询以键入account并:
  • _id约束到帐户ID列表。
  • group.starred约束为true

  • 这将为您提供加星标的列表。要获取更多信息(名称等),请发送查询以键入group并执行以下操作:
  • _id限制为上述组ID。

  • 最后,进行一些客户端处理以将其放在一起,以便程序的下一部分更容易使用。

    关于field - 返回一个自定义字段,其中值取决于Elasticsearch中的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11856029/

    相关文章:

    Elasticsearch - 语料库大小/总体术语频率

    Mysql查询: selecting from two rows in the same field

    php - 如何在提交php时传递动态表单的字段名称和值

    module - 如何从子模块中的结构访问私有(private)字段?

    elasticsearch - Elasticsearch-HTTP设置如何在Kubernetes上进行设置

    javascript - 使用 ajax 时如何保护 Elasticsearch

    mysql:显示两个单独的字段成为一个字段

    php - 在表上创建字段的技巧

    c# - 索引格式每天更改为每周

    search - 在ElasticSearch中实现位置搜索