【问题标题】:manipulate returned fields in elasticsearch在 elasticsearch 中操作返回的字段
【发布时间】:2017-01-17 18:44:29
【问题描述】:

有没有办法从查询中操作(例如连接)返回的字段?

这就是我创建索引的方式:

PUT /megacorp/employee/1
{
    "first_name" : "John",
    "last_name" :  "Smith",
    "age" :        25,
    "about" :      "I love to go rock climbing",
    "interests": [ "sports", "music" ]
}

这就是我查询它的方式:

GET /megacorp/employee/_search
{
  "query": {"match_all": {}}
}

回复是这样的:

{
  "took": 4,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 1,
    "hits": [
      {
        "_index": "megacorp",
        "_type": "employee",
        "_id": "1",
        "_score": 1,
        "_source": {
          "first_name": "John",
          "last_name": "Smith",
          "age": 25,
          "about": "I love to go rock climbing",
          "interests": [
            "sports",
            "music"
          ]
        }
      }
    ]
  }
}

一切正常。

我想要的是连接 _source 中的两个字段并将其作为新字段显示在输出中。

first_name 和 last_name 应该组合成一个新字段“full_name”。如果不在我的索引中创建一个新字段,我无法弄清楚如何做到这一点。我看过“copy_to”,但它要求您在映射中显式设置存储属性,并且您必须在查询中显式请求存储字段。但主要的缺点是,当你同时这样做时,first_name 和 last_name 以逗号分隔返回。我想要一个不错的字符串:“John Smith”

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:
    GET /megacorp/employee/_search
    {
      "query": {"match_all": {}},
      "script_fields": {
        "combined": {
          "script": "_source['first_name'] + ' ' + _source['last_name']"
        }
      }
    }
    

    您需要启用dynamic scripting

    【讨论】:

      【解决方案2】:

      您可以使用script_fields 来实现这一目标

      GET /megacorp/employee/_search
      {
          "query": {"match_all": {}},
          "script_fields" : {
              "full_name" : {
                  "script" : "[doc['first_name'].value, doc['last_name'].value].join(' ')"
              }
          }
      }
      

      您需要确保enable dynamic scripting 才能正常工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-22
        • 2015-09-09
        • 1970-01-01
        • 2012-07-03
        • 2015-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多