Creating a custom analyzer in ElasticSearch Nest client

你。 提交于 2019-12-05 17:00:43

You've added your custom analyzer to your index, but now you need to apply it your fields. You can do this on a field mapping level:

client.CreateIndex("forum-app", c => c
    .NumberOfReplicas(0)
    .NumberOfShards(1)
    .AddMapping<Forum>(e => e
        .MapFromAttributes()
        .Properties(p => p
            .String(s => s.Name(f => f.SomeProperty).Analyzer("formanalyzer")))
    )
    .Analysis(analysis => analysis
        .Analyzers(a => a
            .Add("forumanalyzer", an)
        )
    )
);

Or you can apply it to all fields by default by setting it as the default analyzer of your index:

client.CreateIndex("forum-app", c => c
    .NumberOfReplicas(0)
    .NumberOfShards(1)
    .AddMapping<Forum>(e => e.MapFromAttributes())
    .Analysis(analysis => analysis
        .Analyzers(a => a
            .Add("default", an)
        )
    )
);

More info here in regards to analyzer defaults.

Add a custom analyzer:

var indexSettings = new IndexSettings
{
    NumberOfReplicas = 0, // If this is set to 1 or more, then the index becomes yellow.
    NumberOfShards = 5
};

indexSettings.Analysis = new Analysis();
indexSettings.Analysis.Analyzers = new Analyzers();
indexSettings.Analysis.TokenFilters = new TokenFilters();

var customAnalyzer = new CustomAnalyzer
{
    //CharFilter = new List<string> { "mapping " }, 
    Tokenizer = "standard",
    Filter = new List<string> { "lowercase", "asciifolding" }
};

indexSettings.Analysis.Analyzers.Add("customAnalyzerLowercaseSynonymAsciifolding", customAnalyzer);

And then when creating the index, you specify the analyzer:

var indexConfig = new IndexState
{
    Settings = indexSettings
};

 var createIndexResponse = elasticClient.CreateIndex(indexName, c => c
   .InitializeUsing(indexConfig)
   .Mappings(m => m
       .Map<ElasticsearchModel>(mm => mm
           .Properties(
           p => p
           .Text(t => t.Name(elasticsearchModel => elasticsearchModel.StringTest).Analyzer("customAnalyzerLowercaseSynonymAsciifolding"))                          
           )
       )
   )
);

elasticClient.Refresh(indexName);

And then you query it with something like:

var response = elasticClient.Search<ElasticsearchModel>(s => s
        .Index(indexName)
        .Query(q => q
              .SimpleQueryString(qs => qs
                  .Fields(fs => fs
                       .Field(f => f.StringTest, 4.00)
                  )
                  .Query(query)
                 )
               )
           );

var results = new List<ElasticsearchModel>();
results = response.Hits.Select(hit => hit.Source).ToList();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!