Mauricio Bueno Mauricio Bueno - 3 months ago 8
Node.js Question

Get RANDOM ids with es query with node.js

could anyone help me? Im new in elasticSearch and node.js.

REQUEST

app.get('/', function (req, res, next){
try {
client.search({
index: 'dbcatalogo',
type: 'cars',
size: 10,
body: {
query: {
function_score:{
functions:[{
random_score:{
seed: 1
}
}]
},
match_all: {}
},
sort: {
'AnoModelo': 'desc'
}
}
}).then(function (json) {
res.json(json.hits);
},
function (err) {res.json(error.HandleError(err));});
}
catch (err) { res.json(error.HandleError(err)); }});


RESPONSE

[parse_exception] failed to parse search source. expected field name but got [START_OBJECT]

Answer

You are almost there the match_all needs to be within the query object of function_score as shows in function score below .

Example:

client.search({
    index: 'dbcatalogo',
    type: 'cars',
    size: 10,
    body: {
        query: {
            function_score:{
                functions:[{
                    random_score:{
                        seed: 1
                    }
                }],
                query : {
                    match_all: {}
            }
        }
        },
        sort: {
            'AnoModelo': 'desc'
        }
    }
}).then(function (json) {
    res.json(json.hits);
}

Also if you are sorting on a field other than score the random_score does not make much sense.