cyb*_*ice 9 node.js elasticsearch mongoosastic
我正在尝试使用mongoosastic和Elastic Search创建自动完成,到目前为止,我已经能够使用sense创建它,但我无法将其移植到mongoosastic.
我从ElasticSearch文档中学到了这个教程,并且我能够使用"sense"实现我想要的,其映射看起来像这样:
PUT storys/story/_mapping
{
"story" : {
"properties": {
"description": {
"type": "string"
},
"title": {
"type" : "completion",
"index_analyzer": "simple",
"search_analyzer": "simple"
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
和这样的查询:
GET storys/_suggest
{
"story-suggest": {
"text": "bow",
"completion": {
"field": "title"
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我很难将其移植到mongoosastic.我尝试了以下方法:
var StorySchema = new Schema({
title:{
type: String, es_type:'completion', es_index_analyzer: 'simple', es_search_analyzer: 'simple', es_payloads: true
},
description: {
type: String
}
});
StorySchema.plugin(mongoosastic);
Run Code Online (Sandbox Code Playgroud)
从服务器控制器查询时:
Story.search({
query: {
"match": { title : req.query.q }
},
suggest: {
"my-title-suggestions-1" :{
text: req.query.q,
completion: {
field: 'title'
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
我理解当我使用"sense"时,我正在使用_suggest端点,这就是"故事建议"查询有效的原因.但是,当使用mongoosastic时,我只能使用.search({})来查询我认为像_search这样的行为.但是,我似乎无法找到一种方法来完成我正在寻找自动完成的_suggest行为,当我尝试使用建议进行查询时,我不断在ElasticSearch中解析错误.
有没有办法通过mongoosastic或弹性搜索完成我想要做的事情?
我尝试使用"sense"来做这个,但即使我得到"自动完成"的建议,我也得到了一堆SearchParseExceptions:
GET _search
{
"query": {
"match": { title : "bow" }
},
"suggest": {
"story-suggest": {
"text": "bow",
"completion": {
"field": "title"
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Hus*_*ger 12
以下是基本自动完成的完整解决方案:
将必要的参数添加到架构:
var TagSchema = new Schema({
name: {
type: String,
unique: true,
required: true,
es_type: 'completion',
es_index_analyzer: 'simple',
es_search_analyzer: 'simple',
es_payloads: true
}
});
Run Code Online (Sandbox Code Playgroud)将插件添加到架构并创建模型:
TagSchema.plugin(mongoosastic);
var Tag = mongoose.model('Tag', TagSchema);
Run Code Online (Sandbox Code Playgroud)使用create mapping方法向ES注册映射.如果不执行此步骤,则在创建第一个文档并编制索引时,索引将以默认值注册:
Tag.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);
}
});
Run Code Online (Sandbox Code Playgroud)*可选 - 索引数据库中的现有文档:
var stream = Tag.synchronize(),
count = 0;
stream.on('data', function(err, doc) {
count++;
});
stream.on('close', function() {
console.log('indexed ' + count + ' documents!');
});
stream.on('error', function(err) {
console.log(err);
});
Run Code Online (Sandbox Code Playgroud)使用空查询体搜索并提供两个选项 - 1)使用ES suggest查询,该查询使用我们在模式中创建的"es_completion"字段; 2)size = 0以便空体查询不返回任何标记.
Tag.search(null, {
suggest: {
"tag-suggest": {
"text": "aTermToAutocomplete",
"completion": {
"field": "name"
}
}
},
"size" : 0
},
function(err, results) {
if (err) {
return console.log(JSON.stringify(err, null, 4));
}
return console.log(JSON.stringify(results, null, 4));
});
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
3153 次 |
| 最近记录: |