I'm adding objects to an index dynamically, so they're all indexed using the _default_ mapping. This is problematic because it leads to things like a Guid
being mapped as text
fields rather than as a keyword
. The AutoMap function provided by the NEST client "automagically infers the correct" field from any given datatype, but it does so only when called explicitly. Is there any way to force the _default_ mapping to use the same template as the AutoMap function? Or do I need to add some additional code which loops through all of my possible object types and creates an IndexDescriptor
for each one preemptively?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You could define an index template to apply a mapping to a newly created template
var putIndexTemplateResponse = client.PutIndexTemplate("default", t => t
.Template("*")
.Mappings(m => m
.Map("_default_", tm => tm
.Properties(p => p
.Keyword(k => k
.Name("id")
)
)
)
)
);
This will map the id
property for any type in any newly created index as a keyword field.
If you need something more convention based, you can use dynamic templates with rules to determine how dynamically added fields should be mapped
var createIndexResponse = client.CreateIndex("index-name", t => t
.Mappings(m => m
.Map("_default_", tm => tm
.DynamicTemplates(d => d
.DynamicTemplate("default", dt => dt
.Match("id")
.MatchMappingType("string")
.Mapping(mm => mm
.Keyword(k => k)
)
)
)
)
)
);
Both approaches set mapping conventions within Elasticsearch. If you intend to determine any conventions within your own code e.g. using the visitor pattern, you'll need to explicitly tell Elasticsearch about the resulting mapping.