3

I am trying to get random records using Elastic Search NEST client. Is there any way to do this?

3 Answers 3

3

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()
        )
    )
);
Sign up to request clarification or add additional context in comments.

1 Comment

It seems the API has changed. This works now: client.Search<MyType>(s => s .Query(q => q .FunctionScore(fs => fs .Query(fq => fq.MatchAll()) .Functions(f=>f .RandomScore( Guid.NewGuid().ToString() ) ) ) ) );
2

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

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.