Elasticsearch 基本查询详解

查询(query &filter)

query(查询):query对上下文检索(评分查询)不仅要查找匹配的文档,还要计算每个文档的相关程度,这通常会使其比非评分文档更复杂,而且该查询结果不可缓存

filter(过滤) :filter是对搜索的文档简单检查,这使得它们计算速度非常快。并且可以将常用的filter查询缓存在内存中。

1)查询所有

类似 select * from table

1.通过get请求 url拼接查询条件

--GET  http://localhost:9200/local_mst_student_idx_1/mst_student/_search?q=*&pretty

2.通过JSON 传参查询

-- POST  http://localhost:9200/local_mst_student_idx_1/mst_student/_search?pretty

body传参:{ "query": { "match_all": {} }}

2)单个条件精确查询:

类似select * from table where field = xx

1.match查询

-- POST  http://localhost:9200/local_mst_student_idx_1/mst_student/_search?pretty

body参数:{ "query": { "match":{ "id":"11" } }}

(注:match 跟分词有关系,如果是分词则搜索条为包含类似like查询)

2.term过滤查询

 -- POST  http://localhost:9200/local_mst_student_idx_1/mst_student/_search?pretty

body参数:{ "query": { "term": { "stu_code": "1A0030" } } }

类似select * from table where field in (xx)

terms过滤查询 

-- POST  http://localhost:9200/local_mst_student_idx_1/mst_student/_search?pretty

body参数:{ "query": { "terms": { "stu_age": [ 20,21 ] } }}

(注:该查询对分词字段查询需要根据分词的细度决定能否查询出来,例入查询名称为张三,假设分词器是一元分词则查询不到,你查张或三都能查询出来。)

3)bool 过滤

must :must子句(查询)必须出现在匹配的文档中,并有助于得分,类似于 and。

filter : filter子句(查询)必须出现在匹配的文档中。但是不同于 must查询的分数将被忽略(必须匹配,运行在非评分&过滤模式)。

must_not :不包含条件查询的数据,类似于 not,

should:至少有一个查询条件匹配, 类似于 or。


1.例入我们查询一个where field1 = xx and field2 in (xx,xxx,xxxx);

{

    "query":{

        "bool": {

            "must":[

                {"terms": {"field2":["xx","xxx","xxxx"]}},

                {"term" : {"field1":"xx "}}

            ]

        }

    }

}


2.例入我们查询一个where field1 = xx and field2 =xx or field3 =xx and field4 !=xx;

{

    "query":{

        "bool": {

            "must":[

                {"term" : {"field1":"xx"}},

                {"term" : {"field2":"xx"}}

            ],

            "should":{"term" : {"field3":"xx"}},

            "must_not":{"term" : {"field4":"xx"}}

        }

    }

}

以上都是经过实战后得出结论,请放心参考。类似更多的复杂条件查询,可以模仿以上继续添加条件参数。

4)范围条件查询

gt: > 大于

lt: < 小于

gte: >= 大于或等于

lte: <= 小于或等于

range查询,它允许我们通过一定范围的值来过滤文档。这通常用于数字或日期过滤。例:

①.{ "query":{ "bool": { "filter": { "range":{ "stu_age":{ "gte":20, "lte":22 } } } } }}

5)wildcards :通配符查询,类似模糊查询。

{  "query": {    "wildcard": {      "field": "*xx*"    }  }}

(注:两边加*则匹配添加前后的所有符合的结果,可以使用正则匹配)

6)sort : 排序(sort":{"field ":{"order":"desc"}})

{ "query": { "match_all": {} }, "sort": { "field": { "order": "desc" } }}

7)_source :搜索指定的字段 ("_source":["field1","field2"])

{ "query": { "match_all": {} }, "_source": ["field1", "field2"]}

from : 查询开始参数,from默认为0.

size : 查询条数;size未指定默认为10.

{ "query": { "match_all": {} }, "from": 0, "size": 10}

constant_score:

当我们不关心检索词频率TF对搜索结果排序的影响时,可以使用constant_score将查询语句query或者过滤语句filter包装起来。 检索词频率就是该字段出现的频率。如果 出现频率越高,相关性也越高。 使用 constant_score关键字就是不走评分查询默认评分都是1。可以将上面的查询bool关键字替换成constant_score即可测试。后期详解。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容