操纵elasticsearch

时间:2016-09-09 15:02:40

标签: elasticsearch

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

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

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”,但它要求您在映射中显式设置store属性,并且必须在查询中明确询问存储的字段。但主要的缺点是,当你同时执行这两个操作时,first_name和last_name以逗号分隔返回。我想要一个很好的字符串:“John Smith”

2 个答案:

答案 0 :(得分:0)

GET /megacorp/employee/_search
{
  "query": {"match_all": {}},
  "script_fields": {
    "combined": {
      "script": "_source['first_name'] + ' ' + _source['last_name']"
    }
  }
}

您需要启用dynamic scripting

答案 1 :(得分:0)

您可以使用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才能实现此目的。