如何通过NEST c#将List索引到elasticsearch中

neu*_*t47 1 c# elasticsearch nest

我需要List<Person>通过NEST库将很多条目放入elasticsearch中。我可以使用下面的循环和代码一一放置:

var person = new Person
{
    Id = "1",
    Firstname = "Martijn",
    Lastname = "Laarman"
};

var index = client.Index(person);
Run Code Online (Sandbox Code Playgroud)

但似乎工作真的很慢。有什么办法可以通过NEST更快地做到这一点?

mon*_*_za 5

看一下BulkDescriptor对象。

然后,您可以执行以下操作:

private readonly ElasticClient _client; //needs to be initialized in your code
public void Index(IEnumerable<Person> documents)
    {
        var bulkIndexer = new BulkDescriptor();

        foreach (var document in documents)
        {
            bulkIndexer.Index<Person>(i => i
                .Document(document)
                .Id(document.SearchDocumentId)
                .Index(_indexName));
        }

        _client.Bulk(bulkIndexer);
    }
Run Code Online (Sandbox Code Playgroud)

函数Index,采用您类型的IEnumerable。因此,当您遍历项目以建立索引时,而不是将每个对象单独添加到索引中,请使用此函数将集合传递给它,它将为您批量索引对象。