ElasticSearch 简单语法备忘
Elastic Search 查询备忘
- 使用get请求查询所有数据
GET 127.0.0.1/index/type/_search
- 使用get请求根据id来查询某一条特定的数据
GET 127.0.0.1/index/type/1
表示查询id为1的这一条数据。如果找到了返回这条数据found为true,否则found返回false
// 成功找到数据时返回的数据
{
"_index": "index",
"_type": "type",
"_id": "1",
"_version": 1,
"found": true,
"_source": {
"student_id": 1,
"last_name":"smith",
"first_name":"john",
"age": 23
}
}
// 没有找到数据时的返回数据
{
"_index": "index",
"_type": "type",
"_id": "2",
"found": false
}
- 使用get请求的简单搜索
GET 127.0.0.1/index/type/_search?q=last_name:smith
表示查询last_name为smith的数据,为精确搜索。 在ElasticSearch中这种查询称为查询字符串,如果要查询多个字段可以如下表示
+last_name:smith+first_name:john
如果我们不指定要查询的字段而是直接向es请求一个搜索字符串会这么样呢
GET 127.0.0.1/index/type/_search?q=smith
这样子es会在隐含的_all字段上面查询所有匹配smith的结果,默认情况下es会将所有字段拼接成一个大的字段,分词后匹配。
- 使用post请求的复杂搜索
POST 127.0.0.1/index/type/_search
{
"query": {
"match": {
"last_name": "smith"
}
}
}
上面的请求表示查询last_name中包含smith的数据
更复杂的条件查询
{
"query": {
"bool": {
"must":[
{
"match": {
"last_name": "smith"
}
},
{
"match": {
"first_name": "john"
}
},
{
"should": [
{
"match": {
"age": 15
}
},
{
"match": {
"student_id": 1
}
}
]
}
]
}
}
}
上面的请求展示了bool这中查询中多个条件嵌套的模式,查询结果包含了last_name等于smith,first_name等于john,age为15或者student_id为1的文档。
- 一些关键字总结
-
match 经过分词处理的精确匹配。
-
term 表示精确查询可以处理的范围包括数字、bool类型,文本类型和日期类型,需要注意的时term表示精确匹配。
-
bool bool过滤器,其中可以放置的过滤器分别为must, must_not, should。
-
must must过滤器表示必须匹配,等同于AND。
-
must_not must_not表示必须不匹配,等同于NOT。
-
should should表示必须匹配其中一个,相当于OR。
-
sort 排序,表示按照特定的字段按照什么样的规则进行排序。
example:
{
// ...
"sort": {
"age": "asc"
}
}
//表示查询结果按照age升序排序
- _source 表示返回结果应该返回哪些字段
{
// ...
"_source": ["age", "firsr_name", "last_name"]
}