I am trying to get random records using Elastic Search NEST client. Is there any way to do this?
3 Answers
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()
)
)
);
1 Comment
client.Search<MyType>(s => s .Query(q => q .FunctionScore(fs => fs .Query(fq => fq.MatchAll()) .Functions(f=>f .RandomScore( Guid.NewGuid().ToString() ) ) ) ) );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": {}
}
}
}
Comments
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_scores 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.