Elasticsearch不是免费的模式,现在他们将其称为“写模式”,这对于模式生成过程来说是一个很好的名字。当Elasticsearch接收到具有未知字段的新文档时,它将尝试“有根据的猜测”。
当您使用字段“电子邮件”为第一个文档建立索引时,elasticsearch将查看提供的值并为此字段创建一个映射。然后将值“
test.user@gmail.com”映射到“文本”映射类型。
现在,让我们来看看弹性如何处理带有电子邮件的简单文档。创建一个文档:
POST /auto_mapped_index/_doc{"email": "nobody@example.com"}好奇映射如何?干得好:
GET /auto_mapped_index/_mapping
将回答:
{ "my_first_index" : { "mappings" : { "properties" : { "email" : { "type" : "text", "fields" : { "keyword" : { "type" : "keyword", "ignore_above" : 256 } } } } } }}您会看到,
"type" : "text"它表示映射类型为“文本”,如之前假定的那样。还有一个子字段“关键字”,默认情况下由弹性为文本类型字段自动创建。
现在,我们有2个选项,最简单的一种是查询关键字子字段(请注意点符号):
GET /my_first_index/_search{"query": {"term": {"email.keyword": "nobody@example.com"}}}做完了!
另一个选择是为我们的索引创建一个特定的映射。为此,我们需要一个新的空索引并定义映射。我们可以一口气做到这一点:
PUT /my_second_index/{ "mappings" : { "properties" : { "email" : { "type" : "keyword", "ignore_above" : 256 } } }}现在,让我们填充索引(在这里放置两个文档):
POST /my_second_index/_doc{"email": "nobody@example.com"}POST /my_second_index/_doc{"email": "anybody@example.com"}现在,您未更改的查询应该可以正常工作:
GET /my_second_index/_search{"query": {"term": {"email": "anybody@example.com"}}}响应:
{ "took" : 0, "timed_out" : false, "_shards" : { "total" : 1, "successful" : 1, "skipped" : 0, "failed" : 0 }, "hits" : { "total" : { "value" : 1, "relation" : "eq" }, "max_score" : 0.2876821, "hits" : [ { "_index" : "my_second_index", "_type" : "_doc", "_id" : "OTf3n28BpmGM8iQdGR4j", "_score" : 0.2876821, "_source" : { "email" : "anybody@example.com" } } ] }}


