Elasticsearch/Nest - using MatchPhrase with OnFieldsWithBoost

喜欢而已 提交于 2019-11-30 15:25:26

I don't know Nest, but what you want to do is to use a multi-match query of phrase type, with fields boost.

A quick search on g**gle gave me a syntax like this for the boost part:

.Query(q => q
    .MultiMatch(m => m
        .OnFieldsWithBoost(b => b
            .Add(o => o.MyField, 2.0)
            .Add(o => o.AnotherField, 3.0)
        )
        .Type(TextQueryType.Phrase)
        .Query("my query text")
    )
)

The API must have some sort of type parameter to add the phrase type to this.

Edit: after a quick look in the sources, I found a Type method, added above.

Since I have not found an example of a multimatch query search without defining a given type. I spent a few days trying to work it out and i came up with the solution.

I´m using NEST Library in C#. Here I leave the same method as above but using Generics, and passing a dictionary with the fields and boosts, since you will not have the intellisence writing with the fluent expression. I also added the skip and take (or from and size) methods, the Type of Search and an array of the indexes you want to perform the search.

   var dic = new FluentDictionary<string, double?>();
    dic.Add("Field1", 1.0);
    dic.Add("Field2", 1.0);

   var response = Client.Search<T>(s => s
                                    .Skip(0)
                                    .Take(5)
                                    .Indices(indexes)
                                    .Query(q => q
                                        .MultiMatch(m => m
                                            .OnFieldsWithBoost(b => 
                                            {
                                                foreach (var entry in dic)
                                                    b.Add(entry.Key, entry.Value);     
                                            })
                                            .Type(TextQueryType.Phrase)
                                            .Query("your query text")
                                            )
                                         )
                                    );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!