Elasticsearch NEST client creating multi-field fields with completion

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-06 14:30:49

This is how you can reproduce auto-complete example from attached by you article.

My simple class(we are going to implement auto-complete on Name property)

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

To create multi field mapping in NEST we have to define mapping in such manner:

var indicesOperationResponse = client.CreateIndex(descriptor => descriptor
    .Index(indexName)
    .AddMapping<Document>(m => m
        .Properties(p => p.MultiField(mf => mf
            .Name(n => n.Name)
            .Fields(f => f
                .String(s => s.Name(n => n.Name).Index(FieldIndexOption.Analyzed))
                .String(s => s.Name(n => n.Name.Suffix("sortable")).Index(FieldIndexOption.NotAnalyzed))
                .String(s => s.Name(n => n.Name.Suffix("autocomplete")).IndexAnalyzer("shingle_analyzer"))))))
    .Analysis(a => a
        .Analyzers(b => b.Add("shingle_analyzer", new CustomAnalyzer
        {
            Tokenizer = "standard",
            Filter = new List<string> {"lowercase", "shingle_filter"}
        }))
        .TokenFilters(b => b.Add("shingle_filter", new ShingleTokenFilter
        {
            MinShingleSize = 2,
            MaxShingleSize = 5
        }))));

Let's index some documents:

client.Index(new Document {Id = 1, Name = "Tremors"});
client.Index(new Document { Id = 2, Name = "Tremors 2: Aftershocks" });
client.Index(new Document { Id = 3, Name = "Tremors 3: Back to Perfection" });
client.Index(new Document { Id = 4, Name = "Tremors 4: The Legend Begins" });
client.Index(new Document { Id = 5, Name = "True Blood" });
client.Index(new Document { Id = 6, Name = "Tron" });
client.Index(new Document { Id = 7, Name = "True Grit" });
client.Index(new Document { Id = 8, Name = "Land Before Time" });
client.Index(new Document { Id = 9, Name = "The Shining" });
client.Index(new Document { Id = 10, Name = "Good Burger" });

client.Refresh();

Now, we are ready to write prefix query :)

var searchResponse = client.Search<Document>(s => s
    .Query(q => q
        .Prefix("name.autocomplete", "tr"))
    .SortAscending(sort => sort.Name.Suffix("sortable")));

This query will get us

Tremors 2: Aftershocks
Tremors 3: Back to Perfection
Tremors 4: The Legend Begins
Tron
True Blood
True Grit

Hope this will help you.

Recently, guys from NEST prepared great tutorial about NEST and elasticsearch. There is a part about suggestions, it should be really useful for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!