6

我想使用 NEST 库的 Fluent 接口来创建索引,这涉及设置自定义过滤器、分析器和类型映射。我想避免使用特定于 NEST 的注释来装饰我的类。

我在http://nest.azurewebsites.net/indices/create-indices.htmlhttp://nest.azurewebsites.net/indices/put-mapping.html看到了文档。该文档虽然展示了一些示例,但不足以帮助我弄清楚如何使用 Fluent API 构建一些复杂的索引场景。

我发现http://euphonious-intuition.com/2012/08/more-complicated-mapping-in-elasticsearch/上的教程很有帮助;一些代码展示了如何通过 NEST Fluent 接口构建本教程中的过滤器、分析器和映射来代替直接的 JSON,这将是这个问题的一个很好的答案。

4

1 回答 1

9

你的问题越具体,你收到的答案就越好。尽管如此,这里有一个索引,它设置了一个分析器(带过滤器)和标记器(EdgeNGram),然后使用它们在标签类的名称字段上创建一个自动完成索引。

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

Nest.IElasticClient client = null; // Connect to ElasticSearch

var createResult = client.CreateIndex(indexName, index => index
    .Analysis(analysis => analysis
        .Analyzers(a => a
            .Add(
                "autocomplete",
                new Nest.CustomAnalyzer()
                {
                    Tokenizer = "edgeNGram",
                    Filter = new string[] { "lowercase" }
                }
            )
        )
        .Tokenizers(t => t
            .Add(
                "edgeNGram",
                new Nest.EdgeNGramTokenizer()
                {
                    MinGram = 1,
                    MaxGram = 20
                }
            )
        )
    )
    .AddMapping<Tag>(tmd => tmd
        .Properties(props => props
            .MultiField(p => p
                .Name(t => t.Name)
                .Fields(tf => tf
                    .String(s => s
                        .Name(t => t.Name)
                        .Index(Nest.FieldIndexOption.not_analyzed)
                    )
                    .String(s => s
                        .Name(t => t.Name.Suffix("autocomplete"))
                        .Index(Nest.FieldIndexOption.analyzed)
                        .IndexAnalyzer("autocomplete")
                    )
                )
            )
        )
    )
);

NEST在github上的单元测试项目中也有一个相当完整的映射示例。 https://github.com/elasticsearch/elasticsearch-net/blob/develop/src/Tests/Nest.Tests.Unit/Core/Map/FluentMappingFullExampleTests.cs

编辑:

要查询索引,请执行以下操作:

string queryString = ""; // search string
var results = client.Search<Tag>(s => s
    .Query(q => q
        .Text(tq => tq
            .OnField(t => t.Name.Suffix("autocomplete"))
            .QueryString(queryString)
        )
    )
);
于 2013-10-23T09:12:51.550 回答