简体   繁体   中英

GetById of an index in Elastic search through NEST client

I have a model as UserModel.cs

public class UserModel
{
      public string Id{get; set;}
      public string Name{get; set;}
      public string Age{get;set;}
}

And I am unable to get the User while Searching with his userID.

var clientProvider = new ElasticClientProvider();    
                var response = await clientProvider.Client.IndexAsync(UserModel, i => i
                    .Index("user_index")
                    .Type("user")
                    .Id(userModel.Id)
                );  

                return response.IsValid;

When I am creating a record the _id is getting auto-generated through elastic Search but it is stored as _id a meta field but not under the _source . And I am unable to access _id of meta field through NEST client. Thanks in advance

You can retrieve document by id with help of Get method. Here is an example:

await client.IndexManyAsync(new []
{
    new Document{Id = "1", Name = "name1"}, 
    new Document{Id = "2"}, 
    new Document{Id = "3"}, 
    new Document{Id = "4"}, 
    new Document{Id = "5"}
});

await client.Indices.RefreshAsync();

var getResponse = await client.GetAsync<Document>("1");

System.Console.WriteLine($"Id: {getResponse.Source.Id} Name: {getResponse.Source.Name}");

Prints:

Id: 1 Name: name1

Document class:

public class Document
{
    public string Id { get; set; }
    public string Name { get; set; }
}

Hope that helps.

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