通过NEST客户端在Elasticsearch中获取索引的GetById。

huangapple go评论80阅读模式
英文:

GetById of an index in Elastic search through NEST client

问题

我有一个名为UserModel.cs的模型:

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

当我尝试使用用户的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;

在创建记录时,_id是通过Elasticsearch自动生成的,但它存储在_id元字段下,而不是_source下。我无法通过NEST客户端访问_id元字段。

提前感谢。

英文:

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

答案1

得分: 1

您可以使用Get方法通过ID检索文档。以下是一个示例:

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}");

输出:

Id: 1 Name: name1

Document类:

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

希望这有所帮助。

英文:

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

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

await client.Indices.RefreshAsync();

var getResponse = await client.GetAsync&lt;Document&gt;(&quot;1&quot;);

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

Prints:

Id: 1 Name: name1

Document class:

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

Hope that helps.

huangapple
  • 本文由 发表于 2020年1月6日 18:20:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/59610311.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定