elasticsearch常用命令

获取es的基本信息

curl localhost:9200

新建和删除Index

查看当前节点的所有 Index
curl -X GET 'http://localhost:9200/_cat/indices?v'
创建一个Index
curl -X PUT 'localhost:9200/weather'
删除一个Index
curl -X DELETE 'localhost:9200/weather'

数据操作

在Index里新增一条记录

向指定的/Index/Type 发生PUT请求, /Index/Type/Id, Id 不一定是数字,也可以是任意的字符串

curl -X PUT 'localhost:9200/accounts/person/1' -d '
{
  "user": "张三",
  "title": "工程师",
  "desc": "数据库管理"
}' 
不指定Id, 新增一条记录

注意这里需要使用POST请求,Id是一个随机生成的字符串

curl -X POST 'localhost:9200/accounts/person' -d '
{
  "user": "李四",
  "title": "工程师",
  "desc": "系统管理"
}'
查看一条记录

/Index/Type/Id ,URL 的参数pretty=true表示以易读的格式返回

curl 'localhost:9200/accounts/person/1?pretty=true'
删除记录
curl -X DELETE 'localhost:9200/accounts/person/1'
更新记录
curl -X PUT 'localhost:9200/accounts/person/1' -d '
{
    "user" : "张三",
    "title" : "工程师",
    "desc" : "数据库管理,软件开发"
}' 

数据查询

返回/Index/Type下的所有记录
curl 'localhost:9200/accounts/person/_search'

- took 表示该操作的耗时(单位为毫秒);
- timed_out表示是否超时;
- hits 表示命中的记录;
-- total 表示返回记录数;
-- max_score 表示最高的匹配程度;
-- hits 表示返回的记录组成的数组;
--- _score 表示匹配的程度,默认是按照这个字段降序排列;
全文搜索
curl 'localhost:9200/accounts/person/_search'  -d '
{
  "query" : { "match" : { "desc" : "软件" }}
}'

上面代码使用 Match 查询,指定的匹配条件是desc字段里面包含"软件"这个词;


Elastic 默认一次返回10条结果,可以通过size字段改变这个设置

curl 'localhost:9200/accounts/person/_search'  -d '
{
  "query" : { "match" : { "desc" : "管理" }},
  "size": 1
}'

如果有多个搜索关键字,Elasticsearch 认为它们是 or 关系

curl 'localhost:9200/accounts/person/_search'  -d '
{
  "query" : { "match" : { "desc" : "软件 系统" }}
}'

上面代码搜索的是 软件 or 系统

如果要执行多个关键词的 and 搜索,必须使用布尔查询

curl 'localhost:9200/accounts/person/_search'  -d '
{
  "query": {
    "bool": {
      "must": [
        { "match": { "desc": "软件" } },
        { "match": { "desc": "系统" } }
      ]
    }
  }
}'

如果要在多个字段中搜索同一个关键字:

curl 'localhost:9200/accounts/person/_search'  -d '
{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "desc": "软件"
          }
        },
        {
          "match": {
            "title": "软件"
          }
        }
      ]
    }
  },
  "size": 2
}'

上面代码是在字段"desc"和"title"中搜索关键字"软件"

参考链接

全文搜索引擎 Elasticsearch 入门教程

原文地址:https://www.cnblogs.com/lwmp/p/13193272.html