基本操作
新增索引(指定mapping)
PUT xxx_index
{
"settings": {
"number_of_shards" : 2, "number_of_replicas" : 1
},
"mappings": {
"properties": {
"name":{
"type": "text"
},
"birthday":{
"type": "date"
}
}
}
}
索引mapping新增properties
新增age:
PUT xxx_index/_mapping
{
"dynamic": "strict",
"properties": {
"age": {
"type": "long"
}
}
}
新增group:
PUT xxx_index/_mapping
{
"dynamic": "strict",
"properties": {
"group": {
"type": "keyword"
}
}
}
向索引新增数据
ElasticSearch在7.X版本之前,格式为:
PUT /xxx_index/type_name/id
ElasticSearch在7.X版本去掉了type,所以创建索引和mapping的方式也变了,主要有如下几点变化:
1、索引操作由 PUT {index}/{type}/{id}变成PUT {index}/_doc/{id}
2、Mapping 操作由 PUT {index}/{type}/_mapping变成 PUT {index}/_mapping
3、所有增删改查搜索操作返回结果里面的关键字_type都将被移除
PUT 新增数据
PUT 为新增或者修改
PUT xxx_index/_doc/2
{
"age":9,
"name": "python is good"
}
这种方式会把id为2的数据更新成最新文档,即只包含age和name子字段;另一种数据写入方式 POST
POST 自动生成ID
POST xxx_index/_doc
{
"age":98,
"name": "python3 is good"
}
修改索引指定字段
PUT xxx_index/_doc/2 会覆盖属性,如果只想更新指定的属性值而不影响其他的属性,可以用:
POST xxx_index/_update/2/
{
"doc": {
"name": "java is good"
}
}
备份索引
POST _reindex
{
"source": {
"index": "index1"
},
"dest": {
"index": "index2"
}
}
聚合操作
统计去重后的group值
GET /xxx_index/_search
{
"size": 0,
"aggs": {
"group_values": {
"terms": {
"field": "group","size": 13
}
}
}
}
基于聚合结果过滤
主要使用 post_filter
GET /xxx_index/_search
{
"size": 0,
"aggs": {
"group_values": {
"terms": {
"field": "group"
}
}
},
"post_filter": {
"term": {
"age": 98
}
}
}
Scripting
对数据修改,把 age-1
POST xxx_index/_update/1
{
"script": {
"source": "ctx._source.age -= 1"
}
}
简写:
POST xxx_index/_update/1
{
"script": "ctx._source.age -= 1"
}
上面ctx简单理解是: GET xxx_index/_update/1 获得的内容