我一直在阅读有关属性和字段的以下两个文档:
https://www.elastic.co/guide/zh-CN/elasticsearch/reference/current/multi-fields.html
https://www.elastic.co/guide/zh-CN/elasticsearch/reference/current/properties.html
我了解特定文档中所述的目的(意味着我了解属性的用途,并且了解多字段的目的),但是我并没有真正看到它们实际作用之间的区别。例如,在来自字段文档的代码段显示了如何定义多字段:
PUT my_index
{
"mappings": {
"_doc": {
"properties": {
"city": {
"type": "text",
"fields": {
"raw": {
"type": "keyword"
}
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我将“ fields”改为“ properties”,它的工作原理是否完全一样?
如果仅在示例中替换fields
为properties
,如Biplab所述,Elasticsearch将为您提供一个例外:
"reason": "Failed to parse mapping [doc]: Mapping definition for [city] \
has unsupported parameters: [properties : {raw={type=keyword}}]",
Run Code Online (Sandbox Code Playgroud)
properties
?properties
基本上声明您将在此处发送一个复杂的JSON对象。
使用properties
而不是fields
您的示例中的最接近的映射如下所示:
PUT my_index_with_properties
{
"mappings": {
"doc": {
"properties": {
"city": {
"properties": {
"name": {
"type": "text"
},
"name_keyword": {
"type": "keyword"
}
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您将要插入的文档将如下所示:
POST my_index_with_properties/doc
{
"city": {
"name": "New York",
"name_keyword": "New York"
}
}
Run Code Online (Sandbox Code Playgroud)
请注意"New York"
重复两次。
在这里,您可以使用发出全文查询match
:
POST my_index_with_properties/doc/_search
{
"query": {
"match": {
"city.name": "york"
}
}
}
Run Code Online (Sandbox Code Playgroud)
或使用term
查询进行精确搜索:
POST my_index_with_properties/doc/_search
{
"query": {
"term": {
"city.name_keyword": "New York"
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我们正在查询不同的字段。
fields
?在发布示例时fields
,使用带有的示例,我们可以发送如下所示的文档:
POST my_index/doc
{
"city": "New York"
}
Run Code Online (Sandbox Code Playgroud)
如您所见,没有明确的数据重复。但是实际上,Elasticsearch的下面是为您做的重复。
现在我们可以使用该city
字段进行全文搜索:
POST my_index/doc/_search
{
"query": {
"match": {
"city": "york"
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,它不适用于确切的搜索。以下查询将不返回任何内容,因为该字段city
已被标记化并小写,并且term
查询的参数不是:
POST my_index/doc/_search
{
"query": {
"term": {
"city": "New York"
}
}
}
Run Code Online (Sandbox Code Playgroud)
相反,此确切的搜索查询将起作用:
POST my_index/doc/_search
{
"query": {
"term": {
"city.keyword": "New York"
}
}
}
Run Code Online (Sandbox Code Playgroud)
因为fields
在映射中使用,我们只是要求Elasticsearch再将该city
字段索引为a keyword
,并且必须使用来使用此字段city.keyword
。
因此,作为结论,fields
这只是一种告诉Elasticsearch的方法,您希望它以几种不同的方式处理同一数据字段。例如,当用不同语言为文本编制索引时,它可能会派上用场。
希望有帮助!