Elasticsearch 提供了丰富的查询过滤语句,本文整理了一些经常使用的查询方法。算法
ES 有两种查询方式。本文主要介绍基于DSL语法的查询缓存
match 是一个标准查询,能够查询文本、数字、日期格式的数据。match 查询的一个主要用途是全文检索。ES 5.X 以上的版本默认使用BM25算法进行类似度的计算less
GET /_search { "query": { "match" : { "message" : "hello world" } } }
match_phrase 与match查询不一样,它是精确匹配elasticsearch
GET /_search { "query": { "match_phrase" : { "message" : "this is a test" } } }
multi_match 容许在作match 查询的基础上查询多个字段post
GET /_search { "query":{ "multi_match": { "query": "full text search", "fields": [ "title", "body" ] } } }
term 用于精确值的查询。使用boost参数能够提升指定字段的分数。boost的默认值为1。this
string类型的数据在ES中能够使用text或者keyword的类型来存储。ES存储text类型的数据时会自动分词,而后创建索引。keyword存储数据时,不会分词,直接创建索引。若是须要对string数据进行精确查询,应该使用keyword的类型来存储数据。url
GET /_search { "query":{ "bool":{ "should":[ { "term":{ "status":{ "value":"urgent", "boost":2 } } }, { "term":{ "status":"normal" } } ] } } }
terms 能够指定一个字段的多个精确值。code
GET /_search { "query": { "constant_score" : { "filter" : { "terms" : { "user" : ["kimchy", "elasticsearch"]} } } } }
range 用于须要查询指定范围的内容。range 的经常使用参数有gte (greater-than or equal to), gt (greater-than) ,lte (less-than or equal to) 和 lt (less-than)。ES 的date类型的数值也能够使用range查询。orm
GET /_search { "query": { "range" : { "age" : { "gte" : 10, "lte" : 20, "boost" : 2.0 } } } }
exists 返回在原始字段汇中至少有一个非空值的文档索引
GET /_search { "query": { "exists" : { "field" : "user" } } }
prefix 前缀查询
GET /_search { "query": { "prefix": { "postcode": "W1" } } }
bool 查询能够合并多个过滤条件查询的结果。bool 查询可由 must, should, must not, filter 组合完成
GET /_search { "query":{ "bool":{ "must":{ "term":{ "user":"kimchy" } }, "filter":{ "term":{ "tag":"tech" } }, "must_not":{ "range":{ "age":{ "gte":10, "lte":20 } } }, "should":[ { "term":{ "tag":"wow" } }, { "term":{ "tag":"elasticsearch" } } ] } } }