NEST 聚合类似于 SQL 分组依据

NEST Aggregate similar to SQL Group By

这是我插入到 ES 时的 class

public class BasicDoc
{
    public string Name { get; set; }

    public string Url { get; set; }
}

我成功地使用 NEST 将我的文档插入到 ES。但是我在进行聚合时遇到了麻烦。我的目标是拥有类似于 SQL Group By 的东西。到目前为止我做了什么:

var response = elastic.Search<BasicDoc>(s => s
                    .Aggregations(a => a
                        .Terms("group_by_url", st => st
                            .Field(o => o.Url)
                        ))
);

我尝试根据 BasicDoc.Url 汇总我的文档。假设我的 ES 中有这些:

  1. /api/call1/v1
  2. /api/call2/v1
  3. /api/call1/v1

当我调试时,我的 Nest.BucketAggregate 将有 4 个 Items 键,即 api,call1, call2 and v1。我只期待 2 个 /api/call1/v1 和 /api/call2/v1。我做错了什么?

您目前 analysis set up on your Url property which means that it will be tokenized by the standard analyzer and terms stored in the inverted index. If you need to be able to search on Uri and also need to aggregate on it, then you may consider mapping it as a multi_field 一个字段映射对其进行分析,而另一个不进行分析。这是一个使用 mapping

创建索引的示例
client.CreateIndex("index-name", c => c
    .Mappings(m => m
        .Map<BasicDoc>(mm => mm
            .AutoMap()
            .Properties(p => p
                .String(s => s
                    .Name(n => n.Url)
                    .Fields(f => f
                        .String(ss => ss
                            .Name("raw")
                            .NotAnalyzed()
                        )
                    )
                )
            )
        )
    )
);

执行聚合时,您现在可以使用 Uri 原始字段

var response = client.Search<BasicDoc>(s => s
    .Size(0)
    .Aggregations(a => a
        .Terms("group_by_url", st => st
            .Field(o => o.Url.Suffix("raw"))
        )
    )
);