全局语句
# 查询es中所有的IndexGET _cat/indices#查看集群健康状况GET _cat/health#查看全部索引信息GET _all#查看所有别名对应信息GET _cat/aliases#增加一个库PUT test#删除一个库DELETE test#查询索引信息GET test#集群命令#"action.auto_create_index" 允许根据数据自动创建index#"action.destructive_requires_name" 删除index需要提供name,防止 delete *PUT _cluster/settings{"persistent": {"action.auto_create_index": "true","action.destructive_requires_name": "true"}}#添加分片数量、副本数量、字段映射PUT property_2_t2{"settings" : {"number_of_shards" : 3,"number_of_replicas" : 2},"mappings" : {"properties" : {"deviceNo": {"type": "keyword"},"metric": {"type": "keyword"},"numValue": {"type": "double"},"value": {"type": "keyword"},"objectValue": {"type": "nested"},"timestamp": {"type": "date"}}}}
插入数据
#插入一条商品数据 库名/表名/一条数据的id号PUT /ecommerce/product/1{"name":"puma 公文包","desc":"包","price":210,"producer":"puma producer","tags":"商务 包包"}post /ecommerce/product{"name" : "puma 衬衣","desc" : "衣服","price" : 160,"producer" : "puma producer","tags" : "休闲"}post /ecommerce/product{"name" : "puma 公文包","desc" : "包","price" : 210,"producer" : "puma producer","tags" : "商务"}post /ecommerce/product{"name" : "dior cherry","desc" : "奢侈品","price" : 120,"producer" : "dior producer","tags" : "奢侈"}post /ecommerce/product{"name" : "dior 项链","desc" : "项链","price" : 2700,"producer" : "dior producer","tags" : "奢侈"}post /ecommerce/product{"name" : "dior 包包","desc" : "奢侈品","price" : 2600,"producer" : "dior producer","tags" : "高端"}post /ecommerce/product{"name" : "海澜之家 衬衣","desc" : "商务 休闲","price" : 120,"producer" : "海澜之家 producer","tags" : "休闲"}#指定id生成put /my_index/my_type/1{"test_fields":"test"}get /my_index/my_type/1#自动生成id号post /my_index/my_type{"test_fields":"test2"}
批量插入数据
#批量插入数据PUT /library/book/_bulk?refresh{"index":{"_id": "Leviathan Wakes"}}{"name": "Leviathan Wakes", "author": "James S.A. Corey", "release_date": "2011-06-02", "page_count": 561}{"index":{"_id": "Hyperion"}}{"name": "Hyperion", "author": "Dan Simmons", "release_date": "1989-05-26", "page_count": 482}{"index":{"_id": "Dune"}}{"name": "Dune", "author": "Frank Herbert", "release_date": "1965-06-01", "page_count": 604}POST _bulk{ "index" : { "_index" : "test", "_id" : "1" } }{ "field1" : "value1" }{ "delete" : { "_index" : "test", "_id" : "2" } }{ "create" : { "_index" : "test", "_id" : "3" } }{ "field1" : "value3" }{ "update" : {"_id" : "1", "_index" : "test"} }{ "doc" : {"field2" : "value2"} }
修改
#修改商品数据(全局更新,不推荐)PUT /ecommerce/product/1{"name":"dior cherry","desc":"奢侈品","price":2700,"producer":"dior producer","tags":"奢侈"}#下面这种会丢失数据PUT /ecommerce/product/1{"price":2800}# 推荐使用的更新,只更新指定字段POST /ecommerce/product/3/_update{"doc":{"tags" : "奢侈"}}
删除
#删除数据 按照id删除DELETE /ecommerce/product/1
查询
# 查询格式#es不推荐指定my_type,这跟倒排索引的特性有关系,7.x里面仍然支持这种语法,但是8.x开始使用这种语法会报错,默认只有一个全局的type=_docget /my_index/my_type/_search# 查询商品数据 /index/type/idGET /ecommerce/product/1#查看所有数据,类似于全表扫描GET ecommerce/product/_search# match_all 可以查询到所有文档,是没有查询条件下的默认语句。GET ecommerce/product/_search{"query":{"match_all": {}}}# 查询所有名称里面包含dior的商品,同时按价格进行降序排序,实现分页from开始 size个数GET ecommerce/product/_search{"query":{"match": {"name":"dior"}},"sort":[{"price":{"order":"desc"}}],"from":0,"size":2}# 搜索名称里面包含dior的,并且价格大于250元的商品#如果需要多个查询条件拼接在一起就需要使用bool#bool 过滤可以用来合并多个过滤条件查询结果的布尔逻辑,它包含以下操作符:#must :: 多个查询条件的完全匹配,相当于 and。#must_not :: 多个查询条件的相反匹配,相当于 not。#should :: 至少有一个查询条件匹配, 相当于 or。get ecommerce/product/_search{"query":{"bool": {"must": [{"match": {"name": "dior"}}],"filter": [{"range": {"price": {"gt": 250}}}]}}}# 展示一个全文搜索 查询条件会进行分词dior cherry 3 ,然后取并集get ecommerce/product/_search{"query":{"match": {"name": "dior cherry3"}}}# 不要把条件分词,要精确匹配get ecommerce/product/_search{"query":{"match_phrase": {"name": "dior cherry3"}}}# 把查询结果进行高亮显示# <em>dior</em> <em>cherry3</em>这个标签是默认的标签,可以进行替换,输出到网页get ecommerce/product/_search{"query":{"match": {"name": "dior cherry3"}},"highlight":{"fields": {"name": {}}}}#聚合分析# 计算每个标签tag下商品的数量 select count(*) from product group by tag#对于非keyword类型的列需使用列名.keyword进行聚合查询,不加.keyword用于搜索和分词,加.keyword用于聚合查询#terms 跟 term 有点类似,但 terms 允许指定多个匹配条件。 如果某个字段指定了多个值,那么文档需要一起去做匹配#group_by_tag是个名字随意取get ecommerce/product/_search{"aggs":{"group_by_tag":{"terms": {"field": "tags.keyword"}}}}#查询商品名称里面包含dior的数据,并且按照tag进行分组,计算每个分组下的平均价格# terms 表示分组, avg表示平均值 group_by_tag和avg_price都是一个名字# 先对tags.keyword进行分组,然后按照price的平均值进行倒序get ecommerce/product/_search{"query": {"match": {"name": "dior"}},"aggs": {"group_by_tag": {"terms": {"field": "tags.keyword","order": {"avg_price": "desc"}},"aggs": {"avg_price": {"avg": {"field": "price"}}}}}}# 查询出producer里面包含producer的数据,按照指定的价格区间进行分组,在每个组内再按tag进行分组,分完组以后再求每个组的平均价格,并且按照降序进行排序get ecommerce/product/_search{"query": {"match": {"producer": "producer"}},"aggs": {"group_price_range": {"range": {"field": "price","ranges": [{"from": 50,"to": 250},{"from": 250,"to": 1000},{"from": 1000,"to": 5000}]},"aggs": {"group_by_tag": {"terms": {"field": "tags.keyword","order": {"avg_price": "desc"}},"aggs": {"avg_price": {"avg": {"field": "price"}}}}}}}}#复杂查询示例#查询deviceNo="hjhj" and (metric.keyword="InvertStatus_3" or metric.keyword="OutputFrequency")#聚合查询 group by metric.keyword order by timestamp limit 2 按照metric分组,按照时间倒序,每组抽取两条数据GET property_2_test/_search{"query": {"bool": {"must": [{"term": {"deviceNo.keyword": "hjhj"}},{"bool": {"should": [{"term": {"metric.keyword": "InvertStatus_3"}},{"term": {"metric.keyword": "OutputFrequency"}}]}}]}},"aggs": {"metric_group": {"terms": {"field": "metric.keyword"},"aggs": {"top_2_hits":{"top_hits": {"size": 2,"sort": {"timestamp":{"order":"desc"}}}}}}}}
查询2
#数据准备PUT test1/doc/1{"title": "中国是世界上人口最多的国家"}PUT test1/doc/2{"title": "美国是世界上军事实力最强大的国家"}PUT test1/doc/3{"title": "北京是中国的首都"}#进行分词,中国拆分成“中”和“国”,包含任意一个字就会被匹配到GET test1/doc/_search{"query":{"match":{"title":"中国"}}}#短语查找,即不会分词,必须包含“中国”两个字才会被匹配GET test1/doc/_search{"query":{"match_phrase": {"title": "中国"}}}#我们搜索中国和世界这两个指定词组时,但又不清楚两个词组之间有多少别的词间隔。那么在搜的时候就要留有一些余地。这时就要用到了slop了。相当于正则中的中国.*?世界。这个间隔默认为0GET test1/doc/_search{"query":{"match_phrase":{"title":{"query": "中国世界","slop": 2}}}}#数据准备PUT test2/doc/1{"title": "prefix1","desc": "beautiful girl you are beautiful so"}PUT test2/doc/2{"title": "beautiful","desc": "I like basking on the beach"}#最左前缀查询GET test2/doc/_search{"query": {"match_phrase_prefix": {"desc": "you are bea"}}}#使用短语查询就查不到结果#match匹配会对数据进行分词#match_phrase 不会对数据进行分词,短语查找#match_phrase_prefix 前缀匹配,即查找的数据中包含这个短语,比如 “beautiful girl you are beautiful so”#match_phrase 使用“bea" 查找结果为null#match_phrase_prefix 使用"bea"就可以查找到GET test2/doc/_search{"query": {"match_phrase": {"desc": "you are bea"}}}#max_expansion 参数理解 前缀查询会非常的影响性能,要对结果集进行限制,就加上这个参数。GET test2/doc/_search{"query": {"match_phrase_prefix": {"desc": {"query": "bea","max_expansions": 10}}}}# multi_match是要在多个字段中查询同一个关键字GET test2/doc/_search{"query": {"multi_match": {"query": "beautiful","fields": ["title","desc"]}}}#当设置属性 type:phrase 时 等同于 短语查询GET test1/doc/_search{"query": {"multi_match": {"query": "中国","fields": ["title"],"type": "phrase"}}}#当设置属性 type:phrase_prefix时 等同于 最左前缀查询GET test2/doc/_search{"query": {"multi_match": {"query": "bea","fields": ["desc"],"type": "phrase_prefix"}}}#数据准备POST test/doc{"name" : "wangfei","age" : 27,"desc" : "热天还不让后人不认同"}POST /test/doc/{"doc":{"name" : "wangjifei","age" : 27,"desc" : "生活就像 茫茫海上"}}POST test/doc{"name" : "wangyang","age" : 30,"desc" : "点在我心内的几首歌"}GET test/_search# 单条件查询 name包含wangfeiGET test/doc/_search{"query": {"bool": {"must": [{"match": {"name": "wangfei"}}]}}}#### 多条件组合查询 name包含wangfei and age=27GET test/doc/_search{"query": {"bool": {"must": [{"match": {"name": "wangfei"}},{"match": {"age": 27}}]}}}#name包含wangjifei or age=27GET test/doc/_search{"query": {"bool": {"should": [{"match": {"name": "wangjifei"}},{"match": {"age": 27}}]}}}#name不包含wangjifei and age!=27#转义一下就是name包含wangjifei或age=27的全部不要GET test/doc/_search{"query": {"bool": {"must_not": [{"match": {"name": "wangjifei"}},{"match": {"age": 27}}]}}}#查询name 包含wangjifei and age>=10 and age<27GET test/doc/_search{"query": {"bool": {"must": [{"match": {"name": "wangjifei"}}],"filter": {"range": {"age": {"gte": 10,"lt": 27}}}}}}#数据准备PUT test3/doc/1{"name":"顾老二","age":30,"from": "gu","desc": "皮肤黑、武器长、性格直","tags": ["黑", "长", "直"]}#返回指定列GET test3/doc/_search{"query": {"match": {"name": "顾"}},"_source": ["name","age"]}#高亮显示nameGET test3/doc/_search{"query": {"match": {"name": "顾老二"}},"highlight": {"fields": {"name": {}}}}#自定义高亮标签GET test3/doc/_search{"query": {"match": {"desc": "性格直"}},"highlight": {"pre_tags": "<b class='key' style='color:red'>","post_tags": "</b>","fields": {"desc": {}}}}#查找精确值GET test/doc/_search{"query": {"bool": {"should": [{"term": {"age":27}},{"term":{"age":28}}]}}}# 第二个查询方式GET test/doc/_search{"query": {"terms": {"age": ["27","28"]}}}
别名 alias命令
#查看所有索引GET _alias#查看指定index的索引GET my-data-stream/_alias#为已存在的index添加别名POST _aliases{"actions": [{"add": {"index": "logs-nginx.access-prod","alias": "logs"}}]}#批量添加使用*POST _aliases{"actions": [{"add": {"index": "logs-*","alias": "logs"}}]}#删除别名POST _aliases{"actions": [{"remove": {"index": "logs-nginx.access-prod","alias": "logs"}}]}#同时进行多个操作POST _aliases{"actions": [{"remove": {"index": "logs-nginx.access-prod","alias": "logs"}},{"add": {"index": "logs-my_app-default","alias": "logs"}}]}#在模板里面预先提供alias# Component template with index aliasesPUT _component_template/my-aliases{"template": {"aliases": {"my-alias": {}}}}# Index template with index aliasesPUT _index_template/my-index-template{"index_patterns": ["my-index-*"],"composed_of": ["my-aliases","my-mappings","my-settings"],"template": {"aliases": {"yet-another-alias": {}}}}#创建Index的时候指定alias# PUT <my-index-{now/d}-000001>PUT %3Cmy-index-%7Bnow%2Fd%7D-000001%3E{"aliases": {"my-alias": {}}}
模板命令
ES index 模板
可以使用模板配置预定义的别名,settings和mappings等
创建模板 以前的api是使用_template,现在废弃了推荐使用_index_template,接口是一样的。
模板有两个_component_template和_index_template,_component_template不会直接应用到index,它是作为一个可重用的组件为_index_template提供服务。
#创建模板PUT _index_template/xiot_dev_prop_template{"index_patterns": ["property_*_*"],"template": {"mappings": {"properties": {"deviceNo": {"type": "keyword"},"metric": {"type": "keyword"},"numValue": {"type": "double"},"objectValue": {"type": "nested"},"timestamp": {"type": "date"},"value": {"type": "keyword"}}}}}#index_patterns 应用模板的index模式,template 模板内容#priority优先级 越大越优先,version 版本,_meta元数据PUT _index_template/template_1{"index_patterns": ["te*", "bar*"],"template": {"settings": {"number_of_shards": 1},"mappings": {"_source": {"enabled": true},"properties": {"host_name": {"type": "keyword"},"created_at": {"type": "date","format": "EEE MMM dd HH:mm:ss Z yyyy"}}},"aliases": {"mydata": { }}},"priority": 500,"composed_of": ["component_template1", "runtime_component_template"],"version": 3,"_meta": {"description": "my custom"}}#创建组件模板PUT _component_template/component_template1{"template": {"mappings": {"properties": {"@timestamp": {"type": "date"}}}}}PUT _component_template/runtime_component_template{"template": {"mappings": {"runtime": {"day_of_week": {"type": "keyword","script": {"source": "emit(doc['@timestamp'].value.dayOfWeekEnum.getDisplayName(TextStyle.FULL, Locale.ROOT))"}}}}}}
关于日期的索引名称
参考文档
日期index使用支持 date math index name support
日期index处理器 date-index-name-processor
#生成基于时间的index"date math index name support"#在kibana 控制台使用命令需要使用转义符,使用http api的时候不需要#格式 <static_name{date_math_expr{date_format|time_zone}}>#按年分 property_2_t2_yyyyPUT /<property_2_t2_{now{yyyy}}>PUT /%3Cproperty_2_t2_%7Bnow%7Byyyy%7D%7D%3E#按月分 property_2_t2_yyyy-MMPUT /<property_2_t2_{now{yyyy-MM}}>PUT /%3Cproperty_2_t2_%7Bnow%7Byyyy-MM%7D%7D%3E#按日分 property_2_t2_yyyy-MM-ddPUT /<property_2_t2_{now{yyyy-MM-dd}}>PUT /%3Cproperty_2_t2_%7Bnow%7Byyyy-MM-dd%7D%7D%3E#不分库 property_2_t2PUT property_2_t2PUT %3Cproperty_2_t2_%7Bnow%7Byyyy-MM-dd%7D%7D%3E#基于"date math index name support"的支持 可以根据指定的时间字段生成指定格式的索引"Date index name processor"#field 指定获取时间字段timestamp的数据,date_rounding 时间精确到日,#index_name_prefix 生成的索引的前缀,#index_name_format 时间的格式最后生成的是时间格式是 index_name_prefix+index_name_format#date_formats field指定字段的时间传入格式,这里传入的是时间戳#timezone 指定时区,我们比UTC多8个小时#按年创建PUT _ingest/pipeline/yearlyIndex{"description": "yearly xiot-device-date-time index naming","processors": [{"date_index_name": {"field": "timestamp","date_rounding": "d","timezone": "GMT+8","index_name_prefix": "{{{_index}}}_","index_name_format": "yyyy","date_formats": ["UNIX_MS"]}}]}#按月创建PUT _ingest/pipeline/monthlyIndex{"description": "monthly xiot-device-date-time index naming","processors": [{"date_index_name": {"field": "timestamp","date_rounding": "d","timezone": "GMT+8","index_name_prefix": "{{{_index}}}_","index_name_format": "yyyy-MM","date_formats": ["UNIX_MS"]}}]}#按日创建PUT _ingest/pipeline/dailyIndex{"description": "daily xiot-device-date-time index naming","processors": [{"date_index_name": {"field": "timestamp","date_rounding": "d","timezone": "GMT+8","index_name_prefix": "{{{_index}}}_","index_name_format": "yyyy-MM-dd","date_formats": ["UNIX_MS"]}}]}#使用 pipeline指定你创建的 pipeline的名称POST /property_2_t2/_doc?pipeline=monthlyindex{"metric": "s1","deviceNo": "e32","value": "200","numValue": 200,"timestamp": 1649535178148}
mappings命令
#创建字段映射PUT /my-index-000001{"mappings": {"properties": {"age": { "type": "integer" },"email": { "type": "keyword" },"name": { "type": "text" }}}}#添加到已存在的index字段映射/修改字段映射api,不能修改已有字段的属性,不然索引无效PUT /my-index-000001/_mapping{"properties": {"employee-id": {"type": "keyword","index": false}}}#查看字段映射GET /my-index-000001/_mapping#查看指定字段GET /my-index-000001/_mapping/field/employee-id
其他命令
#使用sql进行查询POST /_sql?format=txt{"query": "SELECT * FROM property_2_t2"}
