elasticsearch search text return full array issue

二次信任 提交于 2019-12-12 03:39:21

问题


I am using mongoosastic for elasticsearch. and i done all setup and its working fine. but problem is result are not getting properly.

FILE:- mongoose and mongoosastic.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var medicineSchema = require('./search')
var mongoosastic = require("mongoosastic");

var UserProfileSchema = new Schema({
    userId: String,
    username: String,
    address: String,
    number: Number,
    task: [{
        name: {
            type: String,
            es_boost: 2.0 // or es_indexed:true
        },
        taskCode: String,
    }]
});
UserProfileSchema.plugin(mongoosastic);
UserProfileSchema.plugin(mongoosastic, {
    host: "localhost",
    port: 9200,
    //  ,curlDebug: true
});
UserProfile = module.exports = mongoose.model('UserProfile', UserProfileSchema);
UserProfile.createMapping(function(err, mapping) {
    if (err) {
        console.log('error creating mapping (you can safely ignore this)');
        console.log(err);
    } else {
        console.log('mapping created!');
        console.log(mapping);
    }
});

And my search Query:

var UserProfileSchema = require('../../app/models/user');
 UserProfileSchema.search({
        query_string: {
            query: name
        }
    }, function(err, result) {
        if (err) {
            callback({
                RESULT_CODE: '-1',
                MESSAGE: 'System error'
            });
        } else {
            callback({
                RESULT_CODE: '1',
                DATA: result
            });
        }
    });

Now my problem is if task array has 3 object and when i search for task string i.e "abc" it will return full collection. with all task But i want only searched string object from task array. i.e name :abc object

......

"task" [{
    name: 'abc',
    taskCode: 123
},{
    name: 'xyz',
    taskCode: 123
},{
    name: 'cdx',
    taskCode: 123
}]


回答1:


The good thing is that your task field is already of type nested in your schema, which is a pre-condition for achieving what you expect.

Now in order to achieve what you want you need to use inner_hits in your query.

UserProfileSchema.search({
  "query": {
    "nested": {
      "path": "task",
      "query": {
        "match": {
          "task.name": name
        }
      },
      "inner_hits": {}        <--- this does the magic
    }
  }
}, ...


来源:https://stackoverflow.com/questions/32288175/elasticsearch-search-text-return-full-array-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!