How do I use the NEST client to configure Elastics

2019-08-20 09:59发布

问题:

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.