您正在寻找的是两个字符串的串联。copy_to
即使它看起来正在这样做,但事实并非如此。和copy_to
从概念上讲,您正在从两者创建一组值field1
and field2
,而不是连接它们。
对于您的用例,您有两种选择:
- use _source转型 https://www.elastic.co/guide/en/elasticsearch/reference/1.6/mapping-transform.html#mapping-transform
- 执行脚本聚合
我会推荐_source
转换,因为我认为这比编写脚本更有效。这意味着,与进行繁重的脚本聚合相比,您在索引时付出的代价很小。
For _source
转型:
PUT /lastseen
{
"mappings": {
"test": {
"transform": {
"script": "ctx._source['all_fields'] = ctx._source['field1'] + ' ' + ctx._source['field2']"
},
"properties": {
"field1": {
"type": "string"
},
"field2": {
"type": "string"
},
"lastseen": {
"type": "long"
},
"all_fields": {
"type": "string",
"index": "not_analyzed"
}
}
}
}
}
和查询:
GET /lastseen/test/_search
{
"aggs": {
"NAME": {
"terms": {
"field": "all_fields",
"size": 10
}
}
}
}
For 脚本聚合,更容易做到(意思是,使用doc['field'].value
而不是更贵的_source.field
) add .raw
子字段到field1
and field2
:
PUT /lastseen
{
"mappings": {
"test": {
"properties": {
"field1": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"field2": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
},
"lastseen": {
"type": "long"
}
}
}
}
}
脚本将使用这些.raw
子字段:
{
"aggs": {
"NAME": {
"terms": {
"script": "doc['field1.raw'].value + ' ' + doc['field2.raw'].value",
"size": 10,
"lang": "groovy"
}
}
}
}
如果没有.raw
子字段(故意创建的not_analyzed
)你需要做这样的事情,这是更昂贵的:
{
"aggs": {
"NAME": {
"terms": {
"script": "_source.field1 + ' ' + _source.field2",
"size": 10,
"lang": "groovy"
}
}
}
}