'How would I able to get search results in elastic search using mongoosastic?

I am trying to use mongoosastic search() but it doesn't give me the result. Data is saved in MongoDB as well as elasticsearch. Below is the mongoose schema

const mongoose     = require('mongoose');
const mongoosastic = require('mongoosastic');
var Schema       = mongoose.Schema;

  mongoose.connect(`mongodb://localhost:27017/elasticsearch`, function(err) {
  if (err) {
    console.error(err);
  }
  console.log('connected.... unless you see an error the line before this!');
});

var ItemSchema = new Schema({
  name          : {type : String, es_indexed : true},
  description   : {type : String, es_indexed : true}
});

ItemSchema.plugin(mongoosastic, {
    "host": "localhost",
    "port": 9200
});

var ItemModel = mongoose.model("Item", ItemSchema);

ItemModel.createMapping((err, mapping) => {
    console.log('mapping created');
});

Search Query that I'm trying to use to get the desired search results.

app.get("/search", (req, res) => {
  console.log(req.query.item);
  ItemModel.search({
    "multi_match": {
        "fields": ["multi_field"],
        "query": req.query.item,
        "fuzziness": "AUTO"
    }
  },
  function (err, results) {
    if (err) {
        return console.log(JSON.stringify(err, null, 4));
    }
    return console.log(JSON.stringify(results, null, 4));
  });
});

Below are the results that are stored on mongoDB.

{ "_id" : ObjectId("627204f3ec9b3ac2cee45c75"), "name" : "water bottle", "description" : "used to store water", "__v" : 0 }
{ "_id" : ObjectId("62720516ec9b3ac2cee45c77"), "name" : "chair", "description" : "used to sit", "__v" : 0 }
{ "_id" : ObjectId("6272060aec9b3ac2cee45c84"), "name" : "Dettol hand sanitizer", "description" : "used to sanitize hands", "__v" : 0 }
{ "_id" : ObjectId("62724a5b9c2c700433afab84"), "name" : "laptop charger", "description" : "used to charge laptop", "__v" : 0 }

Mapping in Elasticsearch

{
  "items" : {
    "mappings" : {
      "properties" : {
        "description" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }
      }
    }
  }
}

Data set saved on elasticsearch Data saved on Elasticsearch



Solution 1:[1]

Finally this Worked for me...

const item = req.params.item;
const results = await ItemModel.search({
    query_string: {
      query: item
    }
  });
  if (results.body.hits.hits) {
    res.json(results.body.hits.hits);
  } else {
    res.status(400).json({ success: false });
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 noobie_coder