Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting on elastic search with node js

For some reason, when I trying to search and sort from an index

This works:

GET indexName/_search
{      
    "sort": [{
      "_uid": { "order": "desc" }
    }],
    "size": 1

}

But, when using node js like this:

elasticClient.search({
     index: indexName,
     type: id,
     sort: [{ "_uid": { "order": "desc" } }],
     size: 1
 })

It returns an error:

No mapping found for [[object Object]] in order to sort on


status :400

I've tried JSON.stringify and all kind of other things, but none of them works

Please, can anyone help me?

like image 928
Guy Levin Avatar asked Aug 03 '16 14:08

Guy Levin


People also ask

How do you sort data in node JS?

Use the sort() method to sort the result in ascending or descending order. The sort() method takes one parameter, an object defining the sorting order.

Can we use Elasticsearch with node js?

Elasticsearch lets you search through vast amounts of data, whether you're implementing real-time search experiences or doing in-depth data analysis. In this tutorial, you'll learn how to integrate Elasticsearch into your Node. js app.

What is Elasticsearch default sort?

In Elasticsearch, the relevance score is represented by the floating-point number returned in the search results as the _score , so the default sort order is _score descending.


3 Answers

Try this instead:

elasticClient.search({
     index: indexName,
     type: id,
     body: {
        sort: [{ "_uid": { "order": "desc" } }],
        size: 1,
        query: { match_all: {}}
     }
 })
like image 138
Val Avatar answered Oct 19 '22 14:10

Val


This also works with the square brackets around it so you can add more than one sort criteria like ['_uid:desc', 'id:asc']

elasticClient.search({
         index: indexName,
         sort: ['_uid:desc'],
         type: id,
         body: {
            size: 1,
            query: { match_all: {}}
         }
     })
like image 39
Martin Naughton Avatar answered Oct 19 '22 16:10

Martin Naughton


This also works :

elasticClient.search({
     index: indexName,
     sort: '_uid:desc',
     type: id,
     body: {
        size: 1,
        query: { match_all: {}}
     }
 })
like image 1
Raja Rajan Avatar answered Oct 19 '22 14:10

Raja Rajan