Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up Id field in Elastic Search / NEST 2.0 via fluent Api

IdField method is deleted in NEST 2.0 / ElasticSearch.NET. I cannot find documentation on how to do it in fluent Api now, in 2.0. Any suggestions? Thank you.

like image 387
Sergey Barskiy Avatar asked Mar 20 '16 22:03

Sergey Barskiy


1 Answers

Id inference in NEST 2.x is very similar to NEST 1.x. There are essentially three ways:

  • Inferring the Id from a property named Id on the POCO.

For example, imagine you have the following type that you index into Elasticsearch

class MyDTO
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string OtherName { get; set; }
}

NEST will look to find a property named Id on the POCO and use the value of this property for the id of the document

  • Using the ElasticsearchType attribute

You can attribute the POCO with ElasticsearchType and use the IdProperty property to signal to NEST to use a different property for the document id. For example,

[ElasticsearchType(IdProperty = nameof(Name))]
class MyOtherDTO
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string OtherName { get; set; }
}

This will use the Name property as the document id

  • Using ConnectionSettings' InferMappingFor<T> method

You can configure the ConnectionSettings to infer the id property for a given type

var connectionSettings = new ConnectionSettings(new Uri("http://localhost:9200"))
    .InferMappingFor<MyOtherDTO>(m => m
        .IdProperty(p => p.OtherName)
    );

This will use the OtherName property as the document id.

This is cached per ConnectionSettings instance so if it is unchanging, I would recommend configuring the settings at startup and using them for the lifetime of the application (you can also use ElasticClient as a singleton too; it's threadsafe).

With InferMappingFor<T> you can also set the index name and type name for a CLR type, as well as rename any properties (i.e. map a POCO property to a different property name in ES mapping) and ignore POCO properties.

The order of precedence for id inference is:

  1. InferMappingFor<T>() IdProperty() on ConnectionSettings
  2. ElasticsearchTypeAttribute on POCO
  3. Inferring Id from a property named Id on the POCO
like image 78
Russ Cam Avatar answered Sep 28 '22 02:09

Russ Cam