pellea
pellea

Reputation: 477

How to specify the index name using attribute using NEST for ElasticSearch lib?

How can I specify the index name using attribute using NEST for ElasticSearch?

Here is the POCO class I used:

[Serializable]
[ElasticsearchType(IdProperty = "msgid")]
public class Message
{
    [PropertyName("msgid")]
    public string Id { get; set; }

    [PropertyName("date")]
    public string Date { get; set; }
}

Upvotes: 1

Views: 2579

Answers (1)

Russ Cam
Russ Cam

Reputation: 125518

You can't specify the index name(s) for a specific POCO type using attributes. You can however specify it on ConnectionSettings using .DefaultMappingFor<T>, where T is your POCO type.

When using BulkAll, you can specify an index name per bulk operation using BufferToBulk(...)

private static void Main()
{
    var defaultIndex = "my-index";
    var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

    var settings = new ConnectionSettings(pool)
        .DefaultIndex(defaultIndex);

    var client = new ElasticClient(settings);

    var bulkAll = client.BulkAll(MyDocuments(), b => b
        .Index(null)
        .Type(null)
        .BufferToBulk((bu, docs) =>
        {
            foreach (var doc in docs)
            {
                bu.Index<MyDocument>(bi => bi
                    .Index(doc.Id % 2 == 0 ? "even-index" : "odd-index")
                    .Document(doc)
               );
            }
        })
        .RefreshOnCompleted()
        .Size(100)
    );

    bulkAll.Wait(TimeSpan.FromMinutes(20), _ => {});
}

private static IEnumerable<MyDocument> MyDocuments()
{
    for (int i = 0; i < 1000; i++)
        yield return new MyDocument(i);
}


public class MyDocument 
{
    public MyDocument(int id)
    {
        Id = id;
        Message = $"message {id}";
    }

    public int Id { get; set; }

    public string Message { get; set; }
}

Upvotes: 1

Related Questions