简体   繁体   中英

How to create document with an index in ElasticSearch using NEST library in .NET?

I am trying to use elastic search for the first time in C# and I am trying to create a document which is similar to a row in sql.

For what I understand, index is similar to a table and document is a row. I tried using CreateDocumentAsync method but it does not have any parameter to pass in the index so I am not sure how do I create a document with a particular index. I cannot use default index because our product can have many indices. First I am checking if the index exists and if it does not then it creates the index and then the document

Some code here


 public async Task<CreateResponse> CreateDocumentAndIndex<T>(T document, string index) where T : class
        {
            CreateResponse response = new(); 
            if (_client.Indices.Exists(index).Exists)
            {
                response = await _client.CreateDocumentAsync<T>(document);
            }
            else
            {
                await _client.IndexAsync(document, idx => idx.Index(index));
                response = await _client.CreateDocumentAsync<T>(document);
            }         
            return response;
        }

Now to use this I have a function that calls this method

var response = await elasticSearchClient.CreateDocumentAndIndex<DbContextEventData>(eventData,"test");

But it gives me an error when it is trying to create a document. Is there a way to pass in index when creating a row/document in elastic search

The question is tagged elasticsearch-5 , so assuming you're using NEST 5.6.6, the index can be specified at the same time as creating a document

var client = new ElasticClient();

var createResponse = await client.CreateAsync(new { foo = "bar" }, c => c
    .Index("my-index") // index
    .Type("_doc") // document type
    .Id("1") // document id
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM