如何在弹性搜索中搜索 [英] How to search in elasticsearch
问题描述
我正在使用mongoosastic作为我的驱动弹性搜索。
我想要搜索一个字符串是否存在于一个字段中,而且我想要搜索一个字段,无论它是否应该完全匹配。
您需要的是 bool query 弹性搜索功能。
我不知道你在哪里停留在这个过程中,但我会尝试描述这个过程。
要将模型编入Elasticsearch只是添加插件。
var mongoose = require('mongoose'),
mongoosastic = require('mongoosastic '),
Schema = mongoose.Schema
var User = new Schema({
name:String,
country:String,
age:Number ,
email:String,
city:String})
User.plugin(mongoosastic)
然后,您可以对模型执行ES搜索,但首先格式化查询。假设您希望每个居住在英国的用户,而不是在伦敦,而您希望匹配30至40岁的用户:
var query = {
bool:{
must:{
term:{country:england}
},
must_not:{
city:{city:london}
},
should:{
range:{
age:{from:30,to:40}
}
}
}
}
您将获得与年龄不相符的用户,但ES将使用评分系统对结果进行排序。
要完成,您将查询发送到ES并处理结果
User.search (query,function(err,users){
if(err){
//处理错误
}
var results = users.hits.hits;
//使用您的命中
}
I want to search in elasticsearch. I am using mongoosastic as my driver for elasticsearch. Where I want to search a string whether it exists in one field and I want to search one more field whether it should match exactly. How can I do it in mongoosastic.
What you need is the bool query feature of Elastic search.
I don't know where you're stuck in the process, but I'll try to describe the process.
To have a model indexed into Elasticsearch simply add the plugin.
var mongoose = require('mongoose'),
mongoosastic = require('mongoosastic'),
Schema = mongoose.Schema
var User = new Schema({
name: String,
country: String,
age: Number,
email: String,
city: String})
User.plugin(mongoosastic)
Then you can perform an ES search on your model, but first you format your query. Let's say you want every user living in England, but not in London, and you would like to match users between 30 and 40 years old :
var query = {
"bool" : {
"must" : {
"term" : { "country" : "england" }
},
"must_not" : {
"city" : { "city" : "london" }
},
"should" : {
"range" : {
"age" : { "from" : 30, "to" : 40}
}
}
}
}
You will get user that don't match your query in term on age, but ES will use a scoring system to sort the results.
To finish you send your query to ES and process the results
User.search(query, function (err, users) {
if (err) {
//Handle error
}
var results = users.hits.hits;
//work with your hits
}
这篇关于如何在弹性搜索中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!