Tuesday 30 May 2017

Creating Index with mapping and retrive sorted field in Elasticsearch

I am new with elasticsearch... and using it in my app. Main tech used in app is JAVASCRIPT and NODEJS. I am facing one issue with retrieving sorted data.

I want to store data like : from, to, time, message. For that i was using....

  client.index({
    index: date,
    id: dateTime,
    type: fileName,
    body: {
      from: senderUser,
      to: reciverUser,
      time: dateTime,
      message: msg,
    }
  }, function(err, resp, status) {
    console.log(resp);
  });

Now, input data looks like below.

index : mon_may_29_2017
id : mon may 29 2017 18:46:53
type : gs
MSG >> 7
senderUser >> shiv
reciverUser >> hp

Data is stored with created index successfully.

{ _index: 'mon_may_29_2017',
  _type: 'gs',
  _id: 'mon may 29 2017 18:46:53 ',
  _version: 1,
  result: 'created',
  _shards: { total: 2, successful: 1, failed: 0 },
  created: true }

Now, Problem is started... When i am using this.... it will retrieve me data as per require... but in RANDOM order.

dNew1 = mon_may_29_2017;

client.search({
    index: dNew1,
    type: fileName,
    size: 1000,
    body: {
      query: {
        match_all: {}
      },
    },
  });

So, after search I got solution like - I need to map data and set field not_analyzed. then sorting. I tried this but not getting results....

// FOR CREATING INDEX :

client.create({
        index: date,
        type: fileName,
        id: dateTime,
        body: {
          "settings": {
            "number_of_shards": 1,
            "number_of_replicas": 0
          },

          mappings: {
            fields: {
              from: {
                type: "text",
                index: "not_analyzed"
              },
              to: {
                type: "string",
                index: "not_analyzed"
              },
              time: {
                type: "string",
                index: "not_analyzed"
              },
              message: {
                type: "text",
                index: "analyzed"
              }
            }
          },

          from: senderUser,
          to: reciverUser,
          time: dateTime,
          message: msg,
        }
      }, function(err, resp, status) {
        console.log(resp);
      });

/////////////////////////////// // FOR SEARCHING QUERY....

 client.search({
    index: dNew1,
    type: fileName,
    size: 1000,
    body: {
      "sort": [{
        "time": {
          "order": "asc"
        }
      }],
      "query": {
        "match_all": {}
      }
    }
  }

So, Please give me proper guide line.... or reference. I red documentation many time but i can't understand related to javascript. I know what i need to do, But i don't know how to do it.

Thanks.



via shivang patel

No comments:

Post a Comment