ScrappyTexas
ScrappyTexas

Reputation: 31

Using Synonyms in Elasticsearch via Nest

I'm having real trouble getting synonyms to work in Elastic using the Nest API.

I've set up my index and all of the appropriate settings, but when I query based a term that should be a synonym, the results appear as if they haven't been applied at all. Here is my set up:

m_objNode = new Uri(Properties.Settings.Default.strLocalElasticSearchURL);
m_objConnectionSettings = new ConnectionSettings(m_objNode, defaultIndex: "myIndex");
m_objElasticClient = new ElasticClient(m_objConnectionSettings);

IndexSettings indexSettings = new IndexSettings();
indexSettings.NumberOfReplicas = 1;
indexSettings.NumberOfShards = 1;

CustomAnalyzer exclamation = new CustomAnalyzer();
exclamation.Tokenizer = "exclamationTokenizer";

indexSettings.Analysis.Tokenizers.Add("exclamationTokenizer", new PatternTokenizer {
    Pattern = @"!"
});

indexSettings.Analysis.Analyzers.Add("exclamation", exclamation);
indexSettings.Analysis.TokenFilters.Add("synonym", new SynonymTokenFilter { Synonyms = new[] { "tire => tyre", "aluminum => aluminium" }, IgnoreCase = true, Tokenizer = "whitespace" });

m_objElasticClient.CreateIndex(c => c
    .Index("myIndex")
    .InitializeUsing(indexSettings)
    .AddMapping<myClass>(m => m
        .MapFromAttributes()
        .IndexAnalyzer("english")
        .SearchAnalyzer("english")                              
        ));

And the objects I'm indexing look like this:

[ElasticType(IdProperty = "JAUniqueKey")]
public class myClass {

    public string JAUniqueKey { get; set; }
    public int JAItemID { get; set; }
    public string JATitle { get; set; }
    public string JABody { get; set; }
}

I'm trying to get the fields JATitle and JABody to be aligned with the synonyms.

Any ideas sure would be welcome.

Thanks, ScrappyT

Upvotes: 1

Views: 2029

Answers (1)

Rob
Rob

Reputation: 9979

You've created token filters correctly but you didn't add it into filters for your custom analyzer.

IndexSettings indexSettings = new IndexSettings();
indexSettings.NumberOfReplicas = 1;
indexSettings.NumberOfShards = 1;

CustomAnalyzer exclamation = new CustomAnalyzer();
exclamation.Tokenizer = "exclamationTokenizer";
exclamation.Filter = new List<string> {"synonym"};
indexSettings.Analysis.Tokenizers.Add(
   "exclamationTokenizer",
    new PatternTokenizer { });

indexSettings.Analysis.Analyzers.Add("exclamation", exclamation);
indexSettings.Analysis.TokenFilters.Add(
    "synonym",
    new SynonymTokenFilter
    {
        Synonyms = new[] { "tire => tyre", "aluminum => aluminium" },
        IgnoreCase = true,
        Tokenizer = "whitespace"
    });

Hope it helps.

Upvotes: 1

Related Questions