Elasticsearch/Nest - using MatchPhrase with OnFiel

2020-02-29 05:01发布

问题:

In my code today I am doing a search like this:

.Query(q => q.QueryString(qs => qs.Query(searchQuery).OnFieldsWithBoost(f => f.Add(b => b.MetaTitle, 5).Add(b => b.RawText, 1))))

My problem is this gives me a very wide search if I search on a phrase like. "The sun is shining". I have tried using MatchPhrase on RawText, instead of QueryString, and that kinda works.

The problem is I still want to search in both MetaTitle and RawText and with the boosting I am using now.

回答1:

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.



回答2:

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")
                                            )
                                         )
                                    );