嘿,我尝试对我的NodeJS项目应用 Elasticsearch ,但收到以下错误:

{ Error: [mapper_parsing_exception] No handler for type [string] declared on field [category]

status: 400,
displayName: 'BadRequest',
message: '[mapper_parsing_exception] No handler for type [string] declared on field [category]',
path: '/products/_mapping/product',
query: {},
body: '{"product":{"properties":{"category":{"type":"string"},"name":{"type":"string"},"price":{"type":"double"},"image":{"type":"string"}}}}',
statusCode: 400,
response: '{"error":{"root_cause":[
 {"type":"mapper_parsing_exception","reason":"No handler for type [string] declared on field [category]"}],"type":"mapper_parsing_exception","reason":"No handler for type [string] declared on field [category]"},"status":400}',
toString: [Function],
toJSON: [Function] }

我的映射代码如下:

product.js 文件:
const mongoose = require('mongoose');
const mongoosastic = require('mongoosastic');
var Schema = mongoose.Schema;
var ProductSchema = new Schema({
   category: {
       type: Schema.Types.ObjectId,
       ref: 'Category'
    },
    name: String,
    price: Number,
    image: String
 });
ProductSchema.plugin(mongoosastic, {
   hosts:[
       'localhost:9200'
   ]
});
var Product = mongoose.model('Product', ProductSchema);
module.exports = {
   Product
}

我的 main.js 文件
Product.createMapping(
{
    "mappings": {
        "products": {
            "_all": {
                "analyzer": "nGram_analyzer",
                 "search_analyzer": "whitespace_analyzer"
            }
        }
    }
},function(err, mapping){
if(err){
    console.log('error creating mapping');
    console.log(err);
}else{
    console.log(mapping);
    console.log("mapping created");
}
});

category.js
var CategorySchema = new Schema({
    name: {
        type: String,
        unique: true,
        lowercase: true
    }
 });

我不知道是什么导致此错误。我认为Mongodb的ObjectId类型有问题。

最佳答案

Elasticsearch不再支持String,而是为text值提供了keywordString。您可以在https://www.elastic.co/blog/strings-are-dead-long-live-strings上方看到@ryanlutgen提供的帖子。

要解决此问题,您只需在创建模型时使用es_type。由于它会导致类别模型出错,因此您应该按以下方式将其除名

var CategorySchema = new Schema({
    name: {
        type: String,
        es_type: 'text'
        unique: true,
        lowercase: true,
        es_index: true
    }
 });

该解决方案从https://github.com/mongoosastic/mongoosastic/issues/436引用

09-25 19:44
查看更多