ElasticSeach查询以检索书籍的所有标签

时间:2017-06-28 10:26:37

标签: c# elasticsearch nest

我有一个ElasticSearch数据库,我有BooksTags个文档。一本书可以有多个标签。

这里是本书的C#类:

[ElasticsearchType(Name = "Book")]
public class Book
{
    [Keyword(Store = false)]
    public string Id{ get; set; }

    [Keyword(Store = false)]
    public string CoverColor{ get; set; } 

    public List<Tag> tags { get; set; }
}

这是标签的ElasticSearch文档:

[ElasticsearchType(Name = "Tag")]
public class Tag
{
    [Keyword(Store = false)]
    public int Id{ get; set; }

    [Keyword(Store = false)]
    public string Name{ get; set; }
}

这是Book文档之一的JSON版本:

{
  "_index": "myindex",
  "_type": "Book",
  "_id": "4d43345fffereredwerw324",
  "_score": 1,
  "_source": {
    "id": "123456",
    "coverColor": "Red",
    "tags": [
      {
        "id": 15,
        "name": "fantasy"
      },
      {
        "id": 2,
        "name": "Science fiction"
      }
    ]
  }
}

我想要的是一个查询,它可以检索所有的书籍颜色而不重复(假设我有两个红色和四个绿色,我应该得到1个红色和1个绿色)并且对于每种颜色我应该得到列表相关标签(例如,相同颜色下的所有标签,基本上)

理想的JSON输出:

result = [
{
   coverColor: "Red",
   tags: [{ id:1, name:"Fantasy"}, {id: 4, name:"Science fiction"}, {id:33, name:"Novel"}]
},
{
   coverColor: "Green",
   tags: [{id: 4, name:"Science fiction"}]
},
{
   coverColor: "White",
   tags: []
}

1 个答案:

答案 0 :(得分:2)

您需要使用我认为的条款汇总。像。的东西。

var result = client.Search<Book>(s => s
    .Aggregations(a => a
        .Terms("colour_agg", st => st
            .Field(o => o.CoverColor)
            .Size(10)
            .ExecutionHint(TermsAggregationExecutionHint.Ordinals)
        )
    )
);

然后从结果集中检索:

var agg = result.Aggs.Terms("colour_agg");

请求类似于:

GET /cars/transactions/_search?search_type=count
{
  "aggs": {
    "colour_agg": {
      "terms": {
        "field": "CoverColor",
        "size": 10
      }
    }
  }
}