copy_to
copy_to 参数允许你将多个字段的值复制到一个组合字段中,然后可以作为单个字段进行查询。
提示
如果你经常搜索多个字段,可以通过使用 copy_to 搜索更少的字段来提高搜索速度。请参阅 尽可能少地搜索字段。
例如,可以将 first_name 和 last_name 字段复制到 full_name 字段,如下所示
PUT my-index-000001
{
"mappings": {
"properties": {
"first_name": {
"type": "text",
"copy_to": "full_name"
},
"last_name": {
"type": "text",
"copy_to": "full_name"
},
"full_name": {
"type": "text"
}
}
}
}
PUT my-index-000001/_doc/1
{
"first_name": "John",
"last_name": "Smith"
}
GET my-index-000001/_search
{
"query": {
"match": {
"full_name": {
"query": "John Smith",
"operator": "and"
}
}
}
}
first_name和last_name字段的值被复制到了full_name字段。- 仍然可以分别对
first_name和last_name字段查询名字和姓氏,但可以通过full_name字段同时查询名字和姓氏。
一些重要注意事项
复制的是字段的 值,而不是词条(即分析过程产生的结果)。
原始的
_source字段不会被修改以显示复制的值。可以将相同的值复制到多个字段,使用
"copy_to": [ "field_1", "field_2" ]你不能使用中间字段进行递归复制。以下配置不会将数据从
field_1复制到field_3PUT bad_example_index{ "mappings": { "properties": { "field_1": { "type": "text", "copy_to": "field_2" }, "field_2": { "type": "text", "copy_to": "field_3" }, "field_3": { "type": "text" } } } }相反,应该从源字段直接复制到多个字段
PUT good_example_index{ "mappings": { "properties": { "field_1": { "type": "text", "copy_to": ["field_2", "field_3"] }, "field_2": { "type": "text" }, "field_3": { "type": "text" } } } }
注意
对于值呈对象形式的字段类型(例如 date_range),不支持 copy_to。
在动态映射中使用 copy_to 时,请考虑以下几点
如果目标字段在索引映射中不存在,则应用常规的 动态映射 行为。默认情况下,当将
dynamic设置为true时,不存在的目标字段将动态添加到索引映射中。如果
dynamic设置为false,则不会将目标字段添加到索引映射中,并且不会复制该值。如果
dynamic设置为strict,复制到不存在的字段将导致错误。如果目标字段是嵌套(nested)字段,则
copy_to字段必须指定嵌套字段的完整路径。省略完整路径将导致strict_dynamic_mapping_exception异常。使用"copy_to": ["parent_field.child_field"]来正确定位嵌套字段。例如
PUT /test_index{ "mappings": { "dynamic": "strict", "properties": { "description": { "properties": { "notes": { "type": "text", "copy_to": [ "description.notes_raw"], "analyzer": "standard", "search_analyzer": "standard" }, "notes_raw": { "type": "keyword" } } } } } }notes字段被复制到notes_raw字段。如果仅目标指向notes_raw而不是description.notes_raw,将会导致strict_dynamic_mapping_exception异常。在此示例中,notes_raw不是在映射的根部定义的,而是在description字段下定义的。如果没有完全限定的路径,Elasticsearch 会将copy_to目标解释为根级字段,而不是description下的嵌套字段。