elasticsearch搜索文本返回完整数组问题

时间:2015-08-29 16:21:59

标签: node.js elasticsearch mongoose mongoosastic

我正在使用 mongoosastic 进行 elasticsearch 。我完成了所有设置并且工作正常。但问题是结果不正确。

文件: - 猫鼬和mongoose。

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);
    }
});

我的搜索查询:

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
            });
        }
    });

的 现在我的问题是,如果任务数组有3个对象,当我搜索任务字符串,即“abc”时,它将返回完整集合。所有任务但我只想从任务数组中搜索字符串对象。,即name:abc object

......

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

1 个答案:

答案 0 :(得分:0)

好处是您的task字段已经在您的架构中属于nested类型,这是达到预期目标的先决条件。

现在,为了实现您的目标,您需要在查询中使用inner_hits

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