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_3
PUT 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
,则复制到不存在的字段将导致错误。如果目标字段是嵌套字段,则
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
下的嵌套字段。