Elasticsearch 接口交互方式

Rest ApI

  • Http Method 指明资源操作类型,如GET/POST/PUT/DELETE等
  • 常用的两种交互方式
    • Curl 命令行
    • kibana DevTools

Index API使用方式

创建索引

  1. PUT /test_index
  2. # 创建索引常用设置
  3. PUT twitter
  4. {
  5. "settings": {
  6. # 主分片
  7. "number_of_shards": "1",
  8. # 副分片
  9. "number_of_replicas": "1",
  10. # 数据从内存刷新到硬盘的间隔
  11. "refresh_interval": "30s",
  12. # 数据分片同步到其他节点
  13. "translog": {
  14. # 30秒同步一次
  15. "sync_interval": "30s",
  16. # 异步默认为同步即使,但非常消耗资源
  17. "durability": "async".
  18. }
  19. }
  20. }

查询索引

  1. GET /test_index
  2. # 查询集群所有索引
  3. GET _cat/indices

删除索引

  1. DELETE /test_index

Document API使用方式

创建文档

  1. PUT /test_index/_doc/1
  2. {
  3. "name": "alex",
  4. "age": 1
  5. }

查询文档

  1. GET /test_indenx/_doc/1
  2. GET /test_index/_search
  3. {
  4. "query": {
  5. "term": {
  6. "_id": "1"
  7. }
  8. }
  9. }

删除文档

  1. DELETE /test_indenx/_doc/1

bulk接口 - 批量插入文档

  1. POST _bulk
  2. { "create" : { "_index" : "test_index", "_id": "1" } }
  3. { "username": "heyang", "age": 22 }
  4. { "create" : { "_index" : "test_index", "_id": "2" } }
  5. { "username": "heyang", "age": 22 }
  6. { "update": { "_index": "test_index", "_id": "2" } }
  7. { "doc": { "username": "luocan" } }
  8. { "delete": { "_index": "test_index", "_id": "1" } }

mget接口 - 批量查询文档(很少用)

  1. GET /_mget
  2. {
  3. "docs" : [
  4. {
  5. "_index" : "test_index",
  6. "_id" : "1"
  7. },
  8. {
  9. "_index" : "test_index",
  10. "_id" : "2"
  11. }
  12. ]
  13. }

索引别名 - Aliases

  • 可以指向多个索引的软链。
  • 简单而重要的功能,为高级功能,如rollover、ILM奠定了基础。
  • 对使用者屏蔽真实索引。

    创建索引别名 - 两种方式

    ```python

    直接在索引里面的template里设置

    PUT /test_index1 { “aliases”: { “test”: {} } }

通过aliase API进行设置

POST _aliases { “actions”: [ { “add”: { “index”: “test_index”, “alias”: “testIndex” } } ] }

<a name="KtgAr"></a>
### 创建查询数据的索引别名
```python
# 通过aliase API进行设置
POST _aliases
{
  "actions": [
    {
      "add": {
        "index": "test_index2",
        "alias": "nginx",
        "filter": {
          "term": {
            "username": "heyang"
          }
        }
      }
    }
  ]
}

# 直接在索引里面的template里设置
PUT test_index3
{
  "mappings": {
    "properties": {
      "username": {
        "type": "keyword"
      }
    }
  },
  "aliases": {
    "test3": {
      "filter": {
        "match": {
          "username": "heyang"
        }
      }
    }
  }
}

删除别名

DELETE test_index2/_alias/*

查询别名

GET _cat/aliases

索引模板讲解与实战

  • 主要用于在新建索引时自动应用预先设定的配置,简化索引创建的操作步骤
  • 可以设定索引的配置和mapping
  • 可以有多个模板,根据oredr设置,order大的覆盖小的配置

    创建模板

  • oredr可以设置,越大会覆盖小的

    PUT _template/test_template
    {
    "order": 0,
    "index_patterns": ["te*", "bar*"],
    "settings": {
      "number_of_shards": 2,
      "number_of_replicas": 1
    },
    "mappings": {
      "properties": {
        "username": {
          "type": "keyword"
        }
      }
    }
    }
    

    删除模板

    DELETE _template/test_template
    

    查询模板

    ```python GET _cat/templates

GET _template/test_template


<a name="DONFQ"></a>
## Dynamic Template讲解与实战

- es可以自动识别文档字段类型,从而降低用户使用成本
<a name="yq8YX"></a>
### DynamicTemplate匹配规则

- match_mapping_type匹配es自动识别的字段类型,如boolean,long,string等
- match,unmatch匹配字段名
- path_match,path_unmatch匹配路径
<a name="Tbo6D"></a>
### 设置DynamicTemplate

- 所有字符串类型都设定为keyword类型,即默认不分词
- 所有以message开头的字段都设定为text类型,即分词
- 所有以aaa_开头的字段都设定为integer类型
```python
PUT test_index5
{
  "mappings": {
    "dynamic_templates": [
      {
        "string_to_keyword": {
          "match_mapping_type": "string",
          "mapping": {
            "type": "keywrod"
          }
        }
      },
      {
        "message_to_text": {
          "match": "message*",
          "mapping": {
            "type": "text"
          }
        }
      },
      {
        "int_to_int": {
          "match": "aaa_*",
          "mapping": {
            "type": "integer"
          }
        }
      }
    ]
  }
}

Reindex

  • 重建所有数据的过程,一般发生在如下情况:

    • mapping设置变更,比如字段类型变化、分词器字典更新等
    • index设置变更,比如分片数更改等
    • 迁移数据

      update_by_query

  • 在现有索引上重建

    POST test_index5/_update_by_query?conflicts=proceed
    

    reindex

  • 在其他索引上重建 ```python POST _reindex { “source”: { “index”: “test_index5” }, “dest”: { “index”: “test_index5_bak” } }

后台执行,会返回任务ID

POST _reindex?wait_for_completion=false { “conflicts”: “proceed”, “source”: { “index”: “test_index5” }, “dest”: { “index”: “test_index5_bak” } }

查询任务ID

GET _tasks/2WzUTIN9S_6_fSi21C49hA:227140


<a name="QWF5V"></a>
## Ingest Pipeline数据处理的使用

- Ingest Node是ES的预处理角色的节点
   - 功能上类似logstash的filter,提供grok、add field、drop field等ETL功能
   - 是在数据落入ES数据节点前的最后一道处理流程
   - 不能像logstash一般可以自由定制input和output,相当于只有logstash filter的能力
      - input可以理解是es coordinating节点
      - output可以理解是es data节点
<a name="4vyhd"></a>
### Ingest Pipeline 简单使用
```python
PUT _ingest/pipeline/my-pipeline
{
  "description": "test",
  "processors": [
    {
      "set": {
        "field": "username",
        "value": "heyang"
      }
    }
  ]
}

Ingest Pipeline Simulate 测试

POST _ingest/pipeline/_simulate
{
  "pipeline": {
    "processors": [
      {
        "set": {
          "field": "username",
          "value": "heyang"
        }
      }
    ]
  },
  "docs": [
    {
      "_source": {
        "username": "ddd"
      }
    }
  ]
}

Ingest Pipeline Processors

Date

  • 负责将日期字符串转换为时间戳

    POST _ingest/pipeline/_simulate
    {
    "pipeline": {
      "processors": [
        {
          "date": {
            "field": "test_date",
            "target_field" : "bak_date",
            "formats": ["yyyy-MM-dd"]
          }
        }
      ]
    },
    "docs": [
      {
        "_source": {
          "test_date": "2020-02-23"
        }
      }
    ]
    }
    

    Drop

  • 符合条件时丢弃该文档,不入库 ```python PUT _ingest/pipeline/my-pip { “description”: “test”, “processors”: [ {

    "drop": {
      "if": "ctx.username == 'Guest'"
    }
    

    }, {

    "drop": {
      "if": """
        if(ctx.tags!=null){
          for(String tag:ctx.tags) {
            if(tag.toLowerCase().contains('prod')) {
              return true;
            }
          }
        }
        return false;
      """
    }
    

    } ] }

POST _reindex { “conflicts”: “proceed”, “source”: { “index”: “test_index5” }, “dest”: { “index”: “test_index6”, “pipeline”: “my-pip” } }

<a name="HNW1K"></a>
### Foreach

- 遍历数组字段的所有值,并做相应的处理
```python
POST _ingest/pipeline/_simulate
{
  "pipeline": {
    "processors": [
      {
        "foreach": {
          "field": "tags",
          "processor": {
            "uppercase": {
              "field": "_ingest._value"
            }
          }
        }
      }
    ]
  },
  "docs": [
    {
      "_source": {
        "tags": ["heyang", "analyzer"]
      }
    }
  ]
}

Grok

  • 基于Grok从原始内容中匹配部分内容到独立的字段 ```python POST _ingest/pipeline/_simulate { “pipeline”: { “processors”: [
    {
      "grok": {
        "field": "message",
        "patterns": [
          "%{IP:client} %{WORD:method} %{URIPATHPARAM:request} %{NUMBER:bytes} %{NUMBER:duration}"
        ]
      }
    }
    
    ] }, “docs”: [ {
    "_source": {
      "message": "55.3.244.1 GET /index.html 15824 0.043"
    }
    
    } ] }
<a name="dxh2d"></a>
### JSON

- 将json字符串转成json对象
```python
POST _ingest/pipeline/_simulate
{
  "pipeline": {
    "processors": [
      {
        "json": {
          "field": "string_source",
          "target_field": "json_source"
        }
      }
    ]
  },
  "docs": [
    {
      "_source": {
        "string_source": "{\"foo\": 2000}"
      }
    }
  ]
}

Remove

  • 删除指定字段

    POST _ingest/pipeline/_simulate
    {
    "pipeline": {
      "processors": [
        {
          "remove": {
            "field": "username"
          }
        }
      ]
    },
    "docs": [
      {
        "_source": {
          "username": "heyang",
          "age": 11
        }
      }
    ]
    }
    

    Rename

  • 字段名重命名

    POST _ingest/pipeline/_simulate
    {
    "pipeline": {
      "processors": [
        {
          "rename": {
            "field": "username",
            "target_field": "user.username"
          }
        }
      ]
    },
    "docs": [
      {
        "_source": {
          "username": "heyang",
          "age": 11
        }
      }
    ]
    }
    

    Set

  • 设置某字段的值,此处可以获取现有字段的值来实现拼接等该功能

    POST _ingest/pipeline/_simulate
    {
    "pipeline": {
      "processors": [
        {
          "set": {
            "field": "set_field",
            "value": "{{last_name}} {{flast_name}}"
          }
        }
      ]
    },
    "docs": [
      {
        "_source": {
          "last_name": "he",
          "flast_name": "yang"
        }
      }
    ]
    }
    

    Split

  • 将字符串分隔为数组

    POST _ingest/pipeline/_simulate
    {
    "pipeline": {
      "processors": [
        {
          "split": {
            "field": "tags",
            "separator": ","
          }
        }
      ]
    },
    "docs": [
      {
        "_source": {
          "tags": "heyang,luocan"
        }
      }
    ]
    }
    

    Script

  • 通过自定义脚本的方式来灵活更改相关字段名和字段值

    POST _ingest/pipeline/_simulate
    {
    "pipeline": {
      "processors": [
        {
          "script": {
            "lang": "painless",
            "source": "ctx.count2 = (ctx.age + ctx.age2 + ctx.count) * params.param_c",
            "params": {
              "param_c": 10
            }
          }
        }
      ]
    },
    "docs": [
      {
        "_source": {
          "age": 1,
          "age2": 3,
          "count": 22
        }
      }
    ]
    }
    

    Ingest Pipeline异常处理

  • 处理异常时,默认会停止并推出后续的处理流程

    • 可以通过增加异常捕捉逻辑,增加自定义的处理流程来解决这个问题
      • 比如处理中报错的数据可以打上另外的标签
      • 或者把报错的数据写入另外一个索引里 ```python

        Processor级别

        POST _ingest/pipeline/_simulate { “pipeline”: { “processors”: [ { “script”: { “lang”: “painless”, “source”: “ctx.count2 = (ctx.age + ctx.age2 + ctx.count) * params.param_c”, “params”: {
        "param_c": 10
        
        }, “on_failure”: [
        {
          "set": {
            "field": "error",
            "value": "{{ _ingest.on_failure_message }}"
          }
        }
        
        ] } } ] }, “docs”: [ { “_source”: { “age”: “1”, “age2”: 3, “count”: 22 } } ] }

pipeline 级别

{ “description” : “my first pipeline with handled exceptions”, “processors” : [ … ], “on_failure” : [ { “set” : { “field” : “_index”, “value” : “failed-{{ _index }}” } } ] }

<a name="O9uZn"></a>
## 练习题
<a name="Q9wLO"></a>
### 1. 请按要求创建索引模板
模板要求如下:

- 模板名为 blog-template,pattern 为 blog-*
- 主分片数为 3,副本数为 1
- 所有字符串类型字段默认均为 keyword
- title 字段类型为 text
- int_ 开头的字段类型为 integer

<a name="txAD8"></a>
### 2. 请按要求创建索引并写入相关文档
索引要求如下:

- 索引名为 blog-2021-01-01
- 创建一个别名 blog 指向 blog-2021-01-01

写入如下文档:(使用 bulk)
```python
[
  {
    "title": "elasticsearch best practice",
    "author_firstname": "tony",
    "author_lastname": "song",
    "tags": "elasticsearch ,logstash",
    "int_age": 18,
    "locale": "zh,en"
  },
  {
    "title": "elastic stack release V5",
    "author_firstname": "shay",
    "author_lastname": "banon",
    "tags": "elk ,elasticsearch,release",
    "int_age": 28,
    "locale": "zhc,en"
  },
  {
    "title": "kibana tutorial",
    "author_firstname": "zen",
    "author_lastname": "wei",
    "tags": "",
    "int_age": 38,
    "locale": "zhc,en"
  }
]

3. 请按如下要求新建一个索引

  • 目前 blog-2021-01-01 索引部分数据有问题,需要做如下修改:
    • 将 author_firstname 和 author_lastname 合并为 author 字段,中间加一个空格,并去除 author_firstname 和 author_lastname
    • tags 字段按照 , 分割为数组,并且去除两边的空格
    • 将 locale 中的 zhc 值改为 zh
    • 增加一个 locale_list 的字段,内容为 locale 字段按照 , 分割为数组,并且去除两边的空格
    • 增加一个字段 locale_len ,记录 locale_list 数组的长度
  • 将修改后的数据写入另一个索引 blog-reindex-2021-01-01 中
  • 将别名 blog 从 blog-2021-01-01 指向 blog-reindex-2021-01-01

答案

PUT _template/blog-template
{
  "index_patterns": [
    "blog-*"
  ],
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1
  },
  "mappings": {
    "dynamic_templates": [
      {
        "text_to_keyword": {
          "match_mapping_type": "string",
          "mapping": {
            "type": "keyword"
          }
        }
      },
      {
        "int_to_integer": {
          "match": "int_*",
          "mapping": {
            "type": "integer"
          }
        }
      }
    ],
     "properties": {
      "title": {
        "type": "text"
      }
    }
  }
}


PUT blog-2021-01-01
{
  "aliases": {
    "blog": {}
  }
}

POST _bulk
{"create":{"_index":"blog","_id":"1"}}
{"title":"elasticsearch best practice","author_firstname":"tony","author_lastname":"song","tags":"elasticsearch ,logstash","int_age":18,"locale":"zh,en"}
{"create":{"_index":"blog","_id":"2"}}
{"title":"elastic stack release V5","author_firstname":"shay","author_lastname":"banon","tags":"elk ,elasticsearch,release","int_age":28,"locale":"zhc,en"}
{"create":{"_index":"blog","_id":"3"}}
{"title":"kibana tutorial","author_firstname":"zen","author_lastname":"wei","tags":"","int_age":38,"locale":"zhc,en"}

PUT _ingest/pipeline/blog-fix-bugs
{
  "description": "fix blog bugs.",
  "processors": [
    {
      "set": {
        "field": "author",
        "value": "{{author_firstname}} {{author_lastname}}"
      }
    },
    {
      "remove": {
        "field": ["author_firstname", "author_lastname"]
      }
    },
    {
      "split": {
        "field": "tags",
        "separator": ","
      }
    },
    {
      "foreach": {
        "field": "tags",
        "processor": {
          "trim": {
            "field": "_ingest._value"
          }
        }
      }
    },
    {
      "gsub": {
        "field": "locale",
        "pattern": "zhc",
        "replacement": "zh"
      }
    },
    {
      "split": {
        "field": "locale",
        "target_field": "locale_list",
        "separator": ","
      }
    },
    {
      "foreach": {
        "field": "locale_list",
        "processor": {
          "trim": {
            "field": "_ingest._value"
          }
        }
      }
    },
    {
      "script": {
        "source": """
          if (ctx.locale_list != null) {
            ctx.locale_len = ctx.locale_list.getLength()
          } else {
            ctx.locale_len = 0
          }
        """
      }
    }
  ]
}

POST _reindex
{
  "conflicts": "proceed", 
  "source": {
    "index": "blog-2021-01-01"
  },
  "dest": {
    "index": "blog-reindex-2021-01-01",
    "pipeline": "blog-fix-bugs"
  }
}

DELETE blog-2021-01-01/_alias/blog

GET _cat/aliases

POST _aliases
{
  "actions": [
    {
      "add": {
        "index": "blog-reindex-2021-01-01",
        "alias": "blog"
      }
    }
  ]
}