总结工作中常用ES脚本

本文汇总了Elasticsearch(ES)的一些常用操作,包括创建和删除索引、设置与获取mapping、查看集群状态、管理索引模板、操作别名以及查询和搜索操作。例如,使用curl创建索引、更新mapping、查看集群健康状态、执行reindex和删除操作。此外,还展示了如何进行复杂的查询,如term搜索后的排序和复合条件查询。

总结工作中常用ES脚本,方便日后查阅,此次脚本应用于es5

增删操作

建立索引

curl -XPUT 'http://192.168.6.122:9200/major_info'

完整创建

curl -X PUT --header 'Content-Type: application/json' --header 'Accept: application/json'  'http://127.0.0.1:9200/farer_index' -d@test.json  

test.json

{
    "settings":{
        "number_of_shards":5,
        "number_of_replicas":0
    },
    "mappings":{
        "article":{
            "dynamic":"strict",
            "_all":{
                "enabled":false
            },
            "properties":{
                "title":{
                    "type":"string",
                    "index":"analyzed",
                    "analyzer":"ik_max_word",
                    "search_analyzer":"ik_max_word"
                },
                "describe":{
                    "type":"string",
                    "index":"analyzed",
                    "analyzer":"ik_max_word",
                    "search_analyzer":"ik_max_word"
                },
                "content":{
                    "type":"string",
                    "index":"analyzed",
                    "analyzer":"ik_max_word",
                    "search_analyzer":"ik_max_word"
                },
                "author":{
                    "type":"string",
                    "index":"no"
                },
                "time":{
                    "type":"date",
                    "index":"not_analyzed",
                    "format":"yyyy-MM-dd HH:mm:ss"
                }
            }
        }
    }
}

 删除索引


curl -XDELETE 'http://192.168.6.122:9200/major_info_202006'

mapping操作

设置mapping

curl -XPUT '192.168.10.183:9200/test2/entities/_mapping' -d@test.json

mapping文件样例

{
      "entities" : {
        "dynamic" : "false",
        "properties" : {
          "concept_id" : {
            "type" : "long",
            "store" : true
          },
          "entity_id" : {
            "type" : "long",
            "store" : true
          },
          "entity_name" : {
            "type" : "text",
            "store" : true
          }
        }
      }
}

拉取mapping


curl -XGET '192.168.6.122:9200/weibo_info_202002/_mapping?pretty' > weibo_info_202002.json

整体状况

查看实体以及数据量


curl -XGET 'http://192.168.6.122:9200/_cat/indices?v'

查看所有节点

curl '10.128.55.188:9200/_cat/nodes?v'

健康状况检查

来源

elasticsearch 查看集群健康、节点状态_u011250186的博客-优快云博客_es查看集群健康状态

 elasticsearch启动后查看是否启动成功:
curl -XGET"http://$(hostname):9200/_cluster/health?pretty=true"

2. 停止elasticsearch应用:
curl -XPOST "http:// $(hostname):9200/_shutdown"

3. 查看集群健康:
curl $(hostname):9200/_cluster/health?pretty

4. 检查集群状态:
curl $(hostname):9200/_cluster/stats?pretty

5. 节点状态:
curl $(hostname):9200/_nodes/process?pretty

curl $(hostname):9200/_nodes/node1/process?pretty

6. 当你不知道有那些属性可以查看时:
curl '$(hostname):9200/_cat/',会返回可以查看的属性


查看指定索引库的健康状态
http://localhost:9200/_cluster/health/index_name?pretty
http://localhost:9200/_cluster/health/index_name,index_name2?pretty

模板相关操作

来源

es 使用curl创建索引模板_laimao8079的博客-优快云博客_es创建索引模板

创建模板 

curl -X PUT --header 'Content-Type: application/json' --header 'Accept: application/json'  'http://127.0.0.1:9200/_template/people_trail' -d@tmp_people_trail.json 

 tmp_people_trail.json

{
    "template":"people_trail*",
    "settings":{
        "index":{
            "number_of_shards":"1",
            "number_of_replicas":"0",
            "analysis":{
                "analyzer":{
                    "pinyin":{
                        "tokenizer":"pinyin_tokenizer"
                    }
                },
                "tokenizer":{
                    "pinyin_tokenizer":{
                        "type":"pinyin",
                        "keep_joined_full_pinyin":true
                    }
                }
            }
        }
    },
    "mappings":{
        "_default_":{
            "_all":{
                "enabled":true,
                "analyzer":"standard"
            },
            "dynamic_templates":[
                {
                    "xms":{
                        "mapping":{
                            "fields":{
                                "py":{
                                    "analyzer":"pinyin",
                                    "type":"text"
                                }
                            },
                            "type":"keyword"
                        },
                        "match_mapping_type":"string",
                        "match":"XM"
                    }
                },
                {
                    "strings":{
                        "match_mapping_type":"string",
                        "mapping":{
                            "type":"keyword",
                            "fields":{
                                "full":{
                                    "type":"text",
                                    "analyzer":"standard"
                                }
                            }
                        }
                    }
                }
            ]
        }
    }
}

新版本

{
  "index_patterns": ["my_index*"],
  "aliases": {
    "my_alias": {}
  },
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 1
  },
  "mappings": {
    "properties": {
      "field1": {
        "type": "text"
      },
      "field2": {
        "type": "keyword"
      }
    }
  }
}

旧版本

{
    "template":"log_info*",
    "mappings":{
        "article":{
            "dynamic":"strict",
            "_all":{
                "enabled":false
            },
            "properties":{
                "title":{
                    "type":"string",
                    "index":"analyzed",
                    "analyzer":"ik_max_word",
                    "search_analyzer":"ik_max_word"
                },
                "author":{
                    "type":"string",
                    "index":"no"
                },
                "itemId":{
                    "type":"long"
                },
                "site":{
                    "type":"keyword"
                },
                "time":{
                    "type":"date",
                    "index":"not_analyzed",
                    "format":"yyyy-MM-dd HH:mm:ss"
                },
                "laudio":{
                    "type":"nested",
                    "properties":{

                    }
                },
                "nfri":{
                    "type":"long"
                }
            }
        }
    }
}

查询所有模板

curl -XGET 127.0.0.1:9200/_cat/templates

查看某一个模板

curl -XGET http://127.0.0.1:9200/_template/article_type?pretty

删除一个索引模板

curl -XDELETE http://127.0.0.1:9200/_template/article_type

添加别名

curl -H "Content-Type: application/json" -XPOST 'http://192.168.6.122:9200/_aliases' -d '
    {
        "actions": [
            {"add": {"index": "major_info_202007_v2", "alias": "main_info"}}
        ]
    }'

查看索引别名


curl -XGET http://192.168.6.122:9200/major_info_202007/_aliases

查看别名下的索引


curl -XGET '192.168.6.122:9200/_alias/major_info'

删除别名

curl -XPOST 'http://192.168.6.122:9200/_aliases' -d '
{
    "actions" : [
        { "remove" : { "index" : "major_info_202007_v2","alias" : "major_info" } }
    ]
}'

查看所有别名

curl -XGET '192.168.6.122:9200/_alias'

查询操作

查询


curl -XGET http://192.168.6.122:9200/major_info_202007/major_info_202007/e7af0e55d1307e021f8eb7594bfd3737?pretty

搜索


curl -XGET 'http://192.168.6.122:9200/major_info/major_info/_search' -d '{"query":{"match":{"uuid":""}}}'

 reindex

curl -XPOST 'localhost:9200/_reindex?pretty' -H 'Content-Type: application/json' -d'
{
  "source": {
    "index": "twitter"
  },
  "dest": {
    "index": "new_twitter"
  }
}
'

按照pubtime倒叙排列

curl -XGET 'http://10.128.55.7:6200/news_ref/news_ref/_search' -d '{ "sort" : [{ "pubtime" : {"order" :"desc"}} ],"from":0,"size":10 }'

term搜索以后排序

curl -XGET 'http://192.168.10.183:9200/info_data/info_data/_search' -d '{"query" : {"term" : { "site_group" : "106" } }, "sort" : [{ "id" : {"order" :"asc"}} ],"from":0,"size":1 }'

根据site_group查询

curl -XGET 'http://192.168.10.183:9200/info_data/info_data/_search' -d '
{
    "query":{
        "term":{
            "site_group":"106"
        }
    },
    "sort":[
        {
            "id":{
                "order":"asc"
            }
        }
    ],
    "from":0,
    "size":1
}
'

根据复合条件查询

curl -XGET 'http://192.168.10.183:9200/info_data/info_data/_search' -d '
{
    "query":{
        "bool":{
            "must":[
                {
                    "term":{
                        "data_type":"1"
                    }
                },
                {
                    "term":{
                        "site_group":"106"
                    }
                }
            ]
        }
    },
    "sort":[
        {
            "id":{
                "order":"asc"
            }
        }
    ],
    "from":0,
    "size":1
}
'

查询删除 delete_by_query

这种删除最快,但是一定要慎重,先查询确认,再删除

curl -X POST "localhost:9200/twitter/_delete_by_query?scroll_size=5000" -H 'Content-Type: application/json' -d'
{
  "query": {
    "term": {
      "user": "kimchy"
    }
  }
}
'

range query 范围查询

curl -XGET 'x.x.55.188:9200/second_short_video_info_ref/second_short_video_info_ref/_search' -d'
{
  "query": {
    "range": {
      "pubtime": { 
        "gte": "2022-03-23 00:00:00", 
        "lte": "2022-03-23 23:59:00"                  
      }
    }
  },
  "size":0
}'

来源

es常用curl整理_谬也的博客-优快云博客_es查询curl

<think>我们正在回答用户关于Shell脚本常用判断符及其用法的问题。根据用户引用的内容,特别是引用[3]和引用[4],我们知道用户关心的是条件测试中的判断符。在Shell脚本中,条件测试主要使用test命令或者[](方括号)来执行。判断符用于比较字符串、整数,检查文件属性等。下面我们将分类介绍常用的判断符及其用法:###一、字符串比较-`=`或`==`:检查两个字符串是否相等。注意在`[]`中,`=`和`==`是等价的,但在`[[]]`中,`==`支持模式匹配(通配符)。-`!=`:检查两个字符串是否不相等。-`-z`:检查字符串长度是否为零(空字符串)。-`-n`:检查字符串长度是否非零(非空字符串)。示例:```bashstr1="hello"str2="world"if["$str1"="$str2"];thenecho"Stringsareequal"elseecho"Stringsarenotequal"fiif[-n"$str1"];thenecho"str1isnotempty"fi```###二、整数比较-`-eq`:等于(equal)-`-ne`:不等于(notequal)-`-gt`:大于(greaterthan)-`-ge`:大于等于(greaterthanorequal)-`-lt`:小于(lessthan)-`-le`:小于等于(lessthanorequal)示例:```bashnum1=10num2=20if[$num1-lt$num2];thenecho"num1islessthannum2"fi```###三、文件测试-`-e`:文件是否存在(existence)-`-f`:是否为普通文件(file)-`-d`:是否为目录(directory)-`-s`:文件存在且大小大于零(size)-`-r`:文件可读(readable)-`-w`:文件可写(writable)-`-x`:文件可执行(executable)-`-L`:文件是否为符号链接(link)示例:```bashfile_path="/path/to/file"if[-f"$file_path"];thenecho"$file_pathisaregularfile"fiif[-x"$file_path"];thenecho"$file_pathisexecutable"fi```###四、逻辑运算符-`!`:逻辑非-`-a`:逻辑与(在`[]`中使用,但推荐使用`&&`在`[[]]`中)-`-o`:逻辑或(在`[]`中使用,但推荐使用`||`在`[[]]`中)在`[[]]`中可以使用`&&`和`||`进行逻辑组合,而且不需要对变量加双引号(因为不会发生单词分割),并且支持通配符匹配。示例:```bashfile="example.txt"if[-f"$file"-a-r"$file"];thenecho"$fileisaregularfileandreadable"fi#使用[[]]更安全且功能更强if[[-f"$file"&&-r"$file"]];thenecho"$fileisaregularfileandreadable"fi#使用正则表达式匹配(在[[]]中)if[["$str"=~^[0-9]+$]];thenecho"$strconsistsofdigitsonly"fi```###五、使用双中括号`[[]]`的优势1.支持模式匹配(使用`==`时,右侧可以包含通配符)2.支持正则表达式匹配(使用`=~`)3.逻辑运算符`&&`和`||`更直观4.字符串比较时不需要引号(不会进行单词分割和路径扩展)示例(模式匹配):```bashfilename="example.txt"if[["$filename"==*.txt]];thenecho"Textfile"fi```###六、注意事项1.在`[]`中使用变量时,变量要用双引号括起来,以防止变量为空或包含空格时出现语法错误。2.使用`[[]]`可以避免很多引号问题,但注意`[[]]`是bash的扩展特性,不是所有shell都支持(如sh),因此脚本首行应指定`#!/bin/bash`。3.对于算术比较,也可以使用`(())`,例如:`if((num1<num2));then...`,这样更符合编程习惯。###七、实例演示根据引用[2]中的例子,使用正则表达式判断用户输入:```bashread-p"Areyourich?yesorno:"ANSWERif[[$ANSWER=~^[Yy]([Ee][Ss])?$]];thenecho"Youarerich"elseecho"GoodGoodStudy,DayDayUp!"fi```###八、总结Shell脚本中的判断符是条件测试的基础,熟练掌握这些判断符对于编写健壮的脚本至关重要。在实际使用中,推荐使用双中括号`[[]]`,它提供了更强大的功能和更简洁的语法。---§§相关问题§§1.在Shell脚本中如何正确比较浮点数?2.如何判断一个字符串是否包含另一个子字符串?3.Shell脚本中`[]`和`[[]]`的主要区别是什么?</think>### Shell脚本常用判断符详解 #### 一、基本判断类型 1. **文件测试判断符** - `-e`:文件是否存在 ```bash if [ -e "/path/file.txt" ]; then echo "文件存在" fi ``` - `-f`:是否为普通文件 - `-d`:是否为目录 - `-r`/`-w`/`-x`:文件是否可读/可写/可执行 - `-s`:文件大小是否大于0字节 ```bash [ -s "log.txt" ] && echo "文件非空" # 单行判断写法[^1] ``` 2. **字符串判断符** - `=` 或 `==`:字符串相等(`==`仅在`[[ ]]`中有效) ```bash if [ "$str1" = "$str2" ]; then ... ``` - `!=`:字符串不相等 - `-z`:字符串长度为零(空字符串) - `-n`:字符串长度非零 ```bash [ -n "$username" ] || echo "用户名为空" # 逻辑或写法 ``` 3. **数值比较判断符** | 符号 | 含义 | 示例 | |------|--------------|--------------------------| | `-eq` | 等于 | `[ $a -eq $b ]` | | `-ne` | 不等于 | `[ $a -ne 0 ]` | | `-gt` | 大于 | `[ $count -gt 10 ]` | | `-ge` | 大于等于 | `[ $age -ge 18 ]` | | `-lt` | 小于 | `[ $temp -lt 100 ]` | | `-le` | 小于等于 | `[ $score -le 60 ]` | #### 二、高级判断技巧 1. **正则匹配(需双中括号)** ```bash if [[ $answer =~ ^[Yy](es)?$ ]]; then echo "用户选择Yes" fi ``` 引用[2]中的正则示例:`[[ $ANSWER =~ ^[Yy]|[Yy][Ee][Ss]$ ]]` 2. **组合条件判断** - `-a`:逻辑与(在单中括号中使用) ```bash [ -f file.txt -a -r file.txt ] # 文件存在且可读 ``` - `-o`:逻辑或 ```bash [ $age -lt 18 -o $age -gt 65 ] # 年龄<18或>65 ``` - `!`:逻辑非 ```bash [ ! -d "/tmp" ] && mkdir /tmp # 目录不存在则创建 ``` #### 三、判断结构对比 | 类型 | 语法 | 特点 | |------------|-----------------------|----------------------------------| | `test`命令 | `test -e file` | 兼容性最好 | | 单中括号 | `[ -e file ]` | 等同于test,需严格空格 | | 双中括号 | `[[ $var == pattern ]]` | 支持通配符/正则,无需变量引号[^4] | #### 四、安全实践要点 1. **变量防护** 始终用双引号包裹变量,避免空值或空格导致的语法错误: ```bash # 错误写法:[ $var = "value" ] # 正确写法:[ "$var" = "value" ] ``` 2. **数值比较替代方案** 使用`(( ))`进行算术比较更直观: ```bash if (( count > MAX_ATTEMPTS )); then echo "超过尝试次数" fi ``` 3. **多条件判断优化** 优先使用`&&`/`||`替代`-a`/`-o`: ```bash [[ -f config.ini && -r config.ini ]] # 比[ -a ]更安全 ``` #### 五、完整示例 ```bash #!/bin/bash # 检查系统状态[^3] if [ $(who | wc -l) -gt 5 ]; then echo "警告:当前登录用户过多" >&2 elif [[ $(df -h / | awk 'NR==2 {print $5}') =~ 9[0-9]% ]]; then echo "磁盘空间即将用尽" elif [ ! -f "/var/lock/process.lock" -a -x "/usr/bin/startup.sh" ]; then /usr/bin/startup.sh fi ``` > **注意**: > 1. 在`[ ]`中每个元素必须用空格分隔:`[ "$a" = "$b" ]` > 2. 使用`[[ ]]`时模式匹配不需要引号:`[[ $file == *.log ]]` > 3. 数学比较推荐使用`(( ))`:`(( counter++ ))`[^3] ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值