前言
本文在编写的时候笔者也是初学es,也只是停留在简单使用层面,更多的是当作笔记记录而已,如果有写错的,希望读者能加以指正。
分享一个可以将sql语句转为es语句的工具:https://tools.pet/sql/sql-es,比如:
ES版本
7.5
Index 新增indexPUT yourIndexName{ “settings”: { “number_of_shards”: 3, “number_of_replicas”: 0, “refresh_interval”: “5s” }, “mappings”: { “properties”: { “application”: { “type”: “text”, //(1)”fields”: { “keyword”: { “type”: “keyword” } } }, “mwtype”: { “type”: “keyword” //(2) } } }}
(1)中type为text代表需要分词,可在下面添加类型为keyword的字段支持精确查找和模糊匹配共存?。
(2)中type为keyword时代表不参与分词,即精确匹配。
查看index的mapping(类比查看mysql的表结构)
创建完index之后可根据 GET /yourIndexName/_mapping 查看具体的映射结构。
新增字段PUT yourIndex/_mapping{ “properties”: { “znodeparent”: { “type”: “text”, “fields”: { “keyword”: { “type”: “keyword” } } } }}
聚合 单字段group byGET youIndexName/_search{ “aggs”: { “NAME”: { “terms”: { “field”: “application.keyword”, “size”: 10 } } }}
size代表返回多少条聚合记录,返回结果中doc_count字段代表有多少个doc匹配到,可以类比为mysql中的count(*)的值
多字段联合匹配?GET yourIndexName/_search{ “aggs”: { “NAME”: { “terms”: { “field”: “application.keyword”, “size”: 10 }, “aggs”: { “NAME1”: { “terms”: { “field”: “ips”, “size”: 10 } } } } }}
查询出来的结果是2个桶的概念,最外层的桶是装所有application的聚合,但每个application本身又是一个桶,里面装的是所有的ips的聚合,结果如下:
{ “key” : “cargo-publish”, “doc_count” : 248, “NAME1” : { “doc_count_error_upper_bound” : 0, “sum_other_doc_count” : 0, “buckets” : [ { “key” : “10.13.65.178”, “doc_count” : 245 }, { “key” : “10.13.65.189:26379”, “doc_count” : 1 }, { “key” : “10.13.65.190:26379”, “doc_count” : 1 }, ] }} Query GET youIndex/_search{ “query”: { “bool”: { “must”: [ { “match”: { “application.keyword”: “ymm-infomin-project” } }, { “match”: { “mwtype”: “17” } }, { “match”: { 美国高防vps “ips.keyword”: “10.13.65.178” } } ], “adjust_pure_negative”: true, “boost”: 1 } }}
公众号
微信搜索“PPShare”,关注公众号。
57645054