检索概览:
ES同MySQL一样拥有众多的查询接口可以帮助用户对指定的查询内容进行匹配检索查询;如精确查询、模糊查询、前缀查询、范围查询、正则表达式匹配查询等。
查询检索子句分为两类:
1)查询语句:执行全文本查询时,基于相关度来评判其匹配结果;查询执行过程复杂,且不会被缓存;
2)过滤语句:执行精确查询时,基于其结果为"yes"或"no"来进行评判;速度快,且结果可被缓存;
一、过滤语句
1)term filter:精确匹配包含指定term的文档;
查询语句:
[root@node2 ~]# curl -XGET -H Content-Type:application/json 'localhost:9200/student/class1/_search?pretty' -d '{
"query":{
"term":{
"age":"25"
}
}
}'
查询结果:
{
"took" : 4, //查询时长,毫秒;
"timed_out" : false, //是否超时;
"_shards" : {
//分片情况;
"total" : 5, //总分片个数;
"successful" : 5, //成功分片的个数;
"skipped" : 0, //跳过的个数;
"failed" : 0 //失败的个数;
},
"hits" : {
//命中数据情况;
"total" : 1, //总命中数据个数;
"max_score" : 1.0, //打分情况;
"hits" : [ //命中数据集;
{
"_index" : "student", //索引名称;
"_type" : "class1", //类型名称;
"_id" : "3", //id情况;
"_score" : 1.0, //打分情况;
"_source" : {
//源数据;
"name" : "Yangguo", //name字段与对应的值;
"age" : 25, //age字段与对应的值;
"sex" : "M" //sex字段与对应的值;
}
}
]
}
}
2)terms filter:用于多值精确匹配
查询语句:
[root@node2 ~]# curl -XGET -H Content-Type:application/json 'localhost:9200/student/class1/_search?pretty' -d '{
"query":{
"terms":{
"age":[25,30]
}
}
}'
查询结果:
{
"took" : 9,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 3,
"max_score" : 1.0,
"hits" : [
{
"_index" : "student",
"_type" : "class1",
"_id" : "5",
"_score" : 1.0,
"_source" : {
"name" : "Xiaofeng",
"age" : 30,
"sex" : "M"
}
},
{
"_index" : "student",
"_type" : "class1",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"name" : "Guojing",
"age" : 30,
"sex" : "M"
}
},
{
"_index" : "student",
"_type" : "class1",
"_id" : "3",
"_score" : 1.0,
"_source" : {
"name" : "Yangguo",
"age" : 25,
"sex" : "M"
}
}
]
}
}
3)range filters:用于在指定的范围内查找数值或时间
gt:大于
lt:小于
get:大于等于
let:小于等于
查询语句:
[root@node2 ~]# curl -XGET -H Content-Type:application/json 'localhost:9200/student/class1/_search?pretty' -d'{
"query":{
"range":{
"age":{
"gte":28,
"lte":30
}
}
}
}'
查询结果:
{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 4,
"max_score"