Home > Enterprise >  ElasticSearch NEST create index mapping dynamically
ElasticSearch NEST create index mapping dynamically

Time:06-30

we have a system in which a client can add new fields to his index mapping in an xml file. When that happens we would take the xml file and based on it create index in the search engine. This is a legacy requirement which we need to support.

So if user uploads xml file

<Group name="some group">
    <Member field="description" type="text"/>
    <Member field="name" type="Date"/>
</Group>

I need to be able to call ElastiSearch to create such an index mapping.

PUT /my-index-000001
{
  "mappings": {
    "properties": {
      "description": { "type": "integer" },  
      "name":        { "type": "date"  }    
    }
  }
}

Now the problem is I'm not sure how to do it in .NET client since it's strongly typed.

I would need to create a class and call Create method to do it.

client.Indices.Create("my-index-000001", c => c
                .Map<SomeClass>(m => m
                    .AutoMap<SomeClass>()
                )

Now this is something I can't do since I don't know what kind of properties will exist in the xml file.

Is there some other way to do it ? Maybe with some kind of a builder for Index class ?

CodePudding user response:

I would just convert XML to Dictionary<PropertyName, IProperty> and use it in client.Indices.PutMappingAsync method to update index definition, something like

var request = new PutMappingRequest("test")
{
    Properties = new Properties(new Dictionary<PropertyName, IProperty>
    {
        { "field1", new TextProperty { Name = fieldName, Analyzer = "standard" } }
    })
};
await client.Indices.PutMappingAsync(request);
  • Related