【问题标题】:Include ObjectId in a search of Elasticsearch在 Elasticsearch 搜索中包含 ObjectId
【发布时间】:2015-11-23 05:23:23
【问题描述】:

我正在使用 ElasticSearch 和 mongoosastic 在 MongoDB 和 ElasticSearch 之间同步数据。我想包含一个模式的属性,这是我研究中的另一个对象:我想显示具有我正在搜索的类别的文章。 这些是我的 2 个模式:ArticleSchema 和 CategorySchema。文章包含一个名为“Categorie”的 Category 对象。

var ArticleSchema = new Schema({
    created: {
        type: Date,
        default: Date.now
    },
    ...
    user: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    categorie: {
        type: Schema.ObjectId,
        es_indexed:true,
        ref: 'Category',
        required: 'Le champ "Categorie" ne peut pas etre vide'
    }
});

var CategorySchema = new Schema({
    name: {
        type: String,
        default: '',
        required: 'Please fill Category name',
        trim: true
    },
    ...
    niveau: {
        type: Number
    }
});

【问题讨论】:

    标签: node.js mongodb elasticsearch mongoosastic


    【解决方案1】:

    您的ArticleSchema 定义只需要正确声明其categorie 属性类型(即不是Schema.ObjectId 而是CategorySchema)。

    如 mongoosastic 文档for nested models 所示,您可以这样做:

    var ArticleSchema = new Schema({
        ...
        categorie: {
            type: [CategorySchema],        <--- change the type to this
            es_indexed:true,
            ref: 'Category',
            required: 'Le champ "Categorie" ne peut pas etre vide'
        }
    });
    

    【讨论】:

    • 是否有另一种方法可以通过 ObjectId 引用文档,而不是通过模式将其创建为子文档? IE。像猫鼬的 ref 和 populate() 之类的东西?
    • 看起来不是开箱即用的。我会看看我是否可以通过水合作用添加该功能并在今晚为它创建一个 PR。您的回答让我更深入地研究了这个问题,并意识到嵌套模型和人口之间的区别。谢谢!
    【解决方案2】:

    我想这就是你要找的https://github.com/mongoosastic/mongoosastic/pull/118

    var Comment = new Schema({
        title: String,
        body: String,
        author: String
    });
    
    
    var User = new Schema({
        name: {type:String, es_indexed:true},
        email: String,
        city: String,
        comments: {type: Schema.Types.ObjectId, ref: 'Comment', es_schema: Comment, es_indexed:true, es_select: 'title body'}
    })
    
    User.plugin(mongoosastic, {
        populate: [
            {path: 'comments', select: 'title body'}
        ]
    })
    

    注意事项:

    1. 您应该向 es_schema 提供您的 ref 架构,以便进行正确的映射
    2. 默认情况下 mongoosastic 将索引整个架构。在您的架构上提供一个 es_select 字段以选择特定字段。
    3. populate 数组是一个包含您传递给 mongoose Model.populate 的相同选项的数组

    【讨论】:

      猜你喜欢
      • 2018-07-24
      • 1970-01-01
      • 2021-04-23
      • 1970-01-01
      • 2021-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-28
      相关资源
      最近更新 更多