jonsagara
(Jon Sagara)
January 22, 2021, 4:41am
1
I'm trying to construct a query against my index that will use function_score
to boost records where fields have certain values. In Kibana Dev Tools, I have the following query that returns 3 hits as expected:
GET /myindex/_search
{
"query": {
"function_score": {
"query": {
"multi_match": {
"query": "somename",
"fields": ["licenseName", "businessName"]
}
}
}
}
}
But when I try to reproduce this with NEST
, no filtering happens, and it just returns all records in the index. To me this looks equivalent, but I must be missing something:
var byNameSearchResult = await _elasticClient.SearchAsync<MyModel>(sr => sr
.Index("myindex")
.Query(qcd => qcd
.FunctionScore(fsqd => fsqd
.Query(fsqcd => fsqcd
.MultiMatch(mmqd => mmqd
.Query(message.Name)
.Fields(fd => fd
.Field(f => f.LicenseName)
.Field(f => f.BusinessName)
)
)
)
)
)
);
Any ideas on what I'm missing in the NEST
query that would make it function like the raw query in Dev Tools?
jonsagara
(Jon Sagara)
January 22, 2021, 5:05pm
2
I think I found the answer. From the docs for function_score :
To use function_score, the user has to define a query and one or more functions, that compute a new score for each document returned by the query.
So, unlike my manual query in Dev Tools, I added a single function to the NEST
query:
var byNameSearchResult = await _elasticClient.SearchAsync<MyModel>(sr => sr
.Index("myindex")
.Query(qcd => qcd
.FunctionScore(fsqd => fsqd
.Query(fsqcd => fsqcd
.MultiMatch(mmqd => mmqd
.Query(message.Name)
.Fields(fd => fd
.Field(f => f.LicenseName)
.Field(f => f.BusinessName)
)
)
)
.Functions(sfd => sfd
.Weight(wfd => wfd
.Filter(wfqcd => wfqcd
.Term(tqd => tqd.Field(tqd => tqd.AccountId).Value(accountId))
)
.Weight(100)
)
)
)
)
);
And I got the query and results I was expecting:
Valid NEST response built from a successful (200) low level call on POST: /myindex/_search?pretty=true&error_trace=true&typed_keys=true
# Audit trail of this API call:
- [1] HealthyResponse: Node: http://192.168.100.2:9200/ Took: 00:00:00.1412548
# Request:
{"query":{"function_score":{"functions":[{"filter":{"term":{"accountId":{"value":"9978f652-700a-4f63-8c71-ea4a11e6ddc9"}}},"weight":100.0}],"query":{"multi_match":{"fields":["licenseName","businessName"],"query":"somename"}}}}}
# Response:
{
"took" : 3,
"timed_out" : false,
"_shards" : {
"total" : 2,
"successful" : 2,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 3,
"relation" : "eq"
},
"max_score" : 10.921473,
"hits" : [
// 3 records
]
}
}
# TCP states:
Established: 82
CloseWait: 14
TimeWait: 5
# ThreadPool statistics:
Worker:
Busy: 1
Free: 32766
Min: 8
Max: 32767
IOCP:
Busy: 1
Free: 999
Min: 8
Max: 1000
system
(system)
Closed
February 19, 2021, 5:05pm
3
This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.