在 Nest 中,如何在索引时指定子文档的父文档?

In Nest, how do I specify a child document's parent document while indexing?

ProductCompany 处于多对一子父关系中:

[ElasticType(Name = "product", IdProperty = "ProductId")]
internal class Product
{
    public int ProductId { get; set; }
    public string Title { get; set; }
}

[ElasticType(Name = "company", IdProperty = "CompanyId")]
public class Company
{
   public int CompanyId { get; set; }
   public string CompanyName { get; set; }
}

Product的映射中,我做了:

Func<PutMappingDescriptor<Product>, PutMappingDescriptor<Product>> descriptor = m => m
               .MapFromAttributes()
               .AllField(a => a.Enabled(false))
               .SetParent<Company>();

我创建了父子:

var company = new Company {
    CompanyId = 1,
    CompanyName = "XYZ Company"
};

var p2 = new Product{
    ProductId = 2,
    Title = "ABC Product"
};

es.Index(company);

那么问题来了,我如何索引p2?只有Index方法,我只能做到es.Index(p2)。但是我在哪里指出 p2 应该在父级 company 下建立索引?

基本上我想要 PUT /myindex/product/2?parent=1.

的 NEST 解决方案

目前我找到的最接近的答案在 中。但是答案使用如下所示的批量插入,其中您在链接中有一个 .Parent 方法来指定父级的 ID:

var bulkResponse = _client.Bulk(b => b
            .Index<Address>(bd => bd.Object(new Address { Name = "Tel Aviv", Id = 1 }).Index("test"))
            .Index<Person>(bd => bd.Index("test").Object(new Person {Id = 5, Address = 1, Name = "Me"}).Parent(1)));

如果您正在寻找 PUT /myindex/product/2?parent=1 请求。 你可以在 NEST 中这样操作:

var indexResponse = client.Index(p2, descriptor => descriptor
    .Parent(company.CompanyId.ToString()));

生成以下对 elasticsearch 的请求

StatusCode : 400,
Method : PUT,
Url : http : //localhost:9200/indexname/product/2?parent=1,
Request : {
    "productId" : 2,
    "title" : "ABC Product"
}