I am trying to get random records using Elastic Search NEST client. Is there any way to do this?
To compliment @pickypg's answer, here's an example of how to compose a function_score
query with a random_score
function in NEST:
client.Search<MyType>(s => s
.Query(q => q
.FunctionScore(fs => fs
.Query(fq => fq.MatchAll())
.RandomScore()
)
)
);
ES 7.x
NEST Way :
var result = _elastic.Search<dynamic>(s => s
.Query(q => q
.FunctionScore(fs => fs.Functions(f => f.RandomScore())
.Query(fq => fq.MatchAll()))));
raw query way :
GET index-name/_search
"size": 1,
"query": {
"function_score": {
"query" : { "match_all": {} },
"random_score": {}
}
}
}
This is more of an Elasticsearch question than one related to NEST. With that in mind, you can do this using a random_score
function in Elasticsearch. random_score
is one of the many function_score
s available in Elasticsearch -- including scripted scores -- and it can be used to control the _score
for each matching document.
Relative to Elasticsearch's REST API
curl -XGET localhost:9200/your-index/your-type/_search -d '{
"query" : {
"function_score": {
"query": { "match_all": {} },
"random_score" : { }
}
},
"size" : 1
}'
You can control the seed used by the random number generator or you can create your own random function score. The current random_score
implementation loads the _uid
field from the index (the unique identifier), which the documentation notes can be memory intensive.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.