学习连接

目录

入门

基础增删改查

{
    "acknowledged": true,//响应结果
    "shards_acknowledged": true,//分片结果
    "index": "shopping"//索引名称
}
health status index    uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   shopping IGEq6KTKR8-Zrk4tGM3PEw   1   1          0            0       208b           208b

各字段含义

{
    "shopping": { // 索引名
        "aliases": {},  // 别名
        "mappings": {},  // 映射:相当于表结构
        "settings": {  // 设置
            "index": {  // 设置-索引
                "creation_date": "1727847341912",  // 设置-索引-创建时间
                "number_of_shards": "1",  // 设置-索引-主分片数量
                "number_of_replicas": "1",  // 设置-索引-复制的文档数量
                "uuid": "IGEq6KTKR8-Zrk4tGM3PEw",  // 设置-索引-uuid
                "version": {  // 设置-索引-版本
                    "created": "7080099" 
                },
                "provided_name": "shopping"  // 设置-索引-提供的名字
            }
        }
    }
}
{
    "acknowledged": true
}
{
    "title":"小米手机",
    "category":"小米",
    "images":"http://www.gulixueyuan.com/xm.jpg",
    "price":3999.00
}
{
    "_index": "shopping",//索引
    "_type": "_doc",//类型-文档
    "_id": "ANQqsHgBaKNfVnMbhZYU",//唯一标识,可以类比为 MySQL 中的主键,随机生成
    "_version": 1,//版本
    "result": "created",//结果,这里的 create 表示创建成功
    "_shards": {//
        "total": 2,//分片 - 总数
        "successful": 1,//分片 - 成功
        "failed": 0//分片 - 失败
    },
    "_seq_no": 0,
    "_primary_term": 1
}

{  "index": {"_index": "shopping", "_id":"1"}}
{  "title": "小米手机",  "category": "小米",  "images": "http://www.gulixueyuan.com/xm.jpg",  "price": 1999}

{  "index": {"_index": "shopping", "_id":"2"}}
{  "title": "小米手机",  "category": "小米",  "images": "http://www.gulixueyuan.com/xm.jpg",  "price": 1999}

🔥warning
  • 添加文档时不指定主键,发送请求的方式必须为 POST,不能是 PUT,否则会发生错误
  • 如果增加数据时明确数据主键,那么请求方式也可以为 PUT。
  • 通过 _doc_create 两种 API 方式来创建文档,主要区别在于 _doc 可以不需要强制指定 _id 参数,_create 必须指定 _id 参数;_doc 在创建文档的时候,如果文档已存在,会先进行删除再创建。而 _create 则会直接报错,提示创建失败。
  • 批量创建时,如果 url 中指定索引 http://localhost:9200/shopping/_bulk,则 json 中可以不指定索引 { "index": {} },(文档 id 是可选的)
  • 需要注意的是,每个 json 数据只能写在一行,且每个文档都必须换行,最后一个也是
{
    "_index": "shopping",
    "_type": "_doc",
    "_id": "1",
    "_version": 1,
    "_seq_no": 1,
    "_primary_term": 1,
    "found": true,
    "_source": {
        "title": "小米手机",
        "category": "小米",
        "images": "http://www.gulixueyuan.com/xm.jpg",
        "price": 3999.00
    }
}
{
    "_index": "shopping",
    "_type": "_doc",
    "_id": "1001",
    "found": false
}
{
    "took": 32,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 2,
            "relation": "eq"
        },
        "max_score": 1.0,
        "hits": [
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "og3LS5IB1orlWxw6XjOX",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 3999.00
                }
            },
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "1",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 3999.00
                }
            }
        ]
    }
}
{
    "title":"华为手机",
    "category":"华为",
    "images":"http://www.gulixueyuan.com/hw.jpg",
    "price":1999.00
}

{
    "_index": "shopping",
    "_type": "_doc",
    "_id": "1",
    "_version": 2, // 版本改变
    "result": "updated",//<-----------updated 表示数据被更新
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "_seq_no": 2,
    "_primary_term": 1
}
{
    "doc": {
        "title":"小米手机",
        "category":"小米"
    }
}
{
    "_index": "shopping",
    "_type": "_doc",
    "_id": "1",
    "_version": 3,  // 版本也跟着变
    "result": "updated",//<-----------updated 表示数据被更新
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "_seq_no": 3,
    "_primary_term": 1
}
{
    "_index": "shopping",
    "_type": "_doc",
    "_id": "1",
    "_version": 4,
    "result": "deleted",//<---删除成功
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "_seq_no": 4,
    "_primary_term": 1
}
{
    "_index": "shopping",
    "_type": "_doc",
    "_id": "1",
    "found": false
}

查询

{
    "query":{
        "match":{ // 匹配
            "category":"小米"
        }
    }
}

// 查找所有文档
{
    "query":{
        "match_all":{}
    }
}
{
    "query":{
        "match_all":{}
    },
    "_source":["title"] // 返回 title 字段
}
{
    "query":{
        "match_all":{}
    },
    "from":0,
    "size":2
}
{
    "query":{
        "match_all":{}
    },
    "sort":{
        "price":{
            "order":"desc" // 或者 asc
        }
    }
}
{
    "query":{
        "bool":{
            "must":[ // 相当于 and
                {
                    "match":{
                        "category":"小米"
                    }
                },
                {
                    "match":{
                        "price":3999
                    }
                }
            ]
        }
    }
}
{
    "query": {
        "bool": {
            "should": [ // 相当于 or
                {
                    "match": { // 相当于 =
                        "category": "小米"
                    }
                },
                {
                    "match": {
                        "category": "华为"
                    }
                }
            ]
        }
    }
}
{
    "query": {
        "bool": {
            "should": [ // 相当于 or
                {
                    "match": { // 相当于 =
                        "category": "小米"
                    }
                },
                {
                    "match": {
                        "category": "华为"
                    }
                }
            ],
            "filter": { // 过滤相当于 > < >= <=
                "range": {
                    "price": {
                        "gt": 1000
                    }
                }
            }
        }
    }
}
{
    "query":{
        "match":{ // 匹配
            "category":"小华"
        }
    }
}
{
    "query":{
        "match_phrase":{ // 匹配
            "category":"为"
        }
    }
}
{
    "query":{
        "match_phrase":{ // 匹配
            "category":"为"
        }
    },
    "highlight":{
        "fields":{
            "category":{} // 高亮这个字段
        }
    }
}
"hits": [
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "qA3-S5IB1orlWxw6JzOf",
                "_score": 0.6931471,
                "_source": {
                    "title": "华为手机",
                    "category": "华为",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 1999
                },
                "highlight": {
                    "category": [
                        "华<em>为</em>" // 高亮一个 为 字
                    ]
                }
            },
{
    "aggs":{ // 聚合操作
        "price_group":{ // 聚合的名称,聚合后的字段名
            "terms":{ // 分组计数,还有 avg, max, min, sum
                "field":"price" // 分组字段
            }
        }
    },
    "size":0 // 默认返回结果带原始数据,不想附带原始数据,设置 size 为 0
}
{
    "took": 7,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 6,
            "relation": "eq"
        },
        "max_score": null,
        "hits": []
    },
    "aggregations": {
        "price_group": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
                {
                    "key": 1999.0,
                    "doc_count": 5
                },
                {
                    "key": 3999.0,
                    "doc_count": 1
                }
            ]
        }
    }
}

映射

{
    "properties":{
        "name":{
            "type":"text", // 字段类型
            "index": true
        },
        "sex":{
            "type":"keyword",
            "index":true
        },
        "tel":{
            "type":"keyword",
            "index":false // false 表示该字段不会建立倒排索引,无法用于全文检索,但仍可返回该字段
        }
    }
}
{
    "name":"小米",
    "sex":"男的",
    "tel":"110"
}
{
    "query":{
        "match":{
            "sex":"男"
        }
    }
}
// 查询结果
{
    "took": 1,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 0,
            "relation": "eq"
        },
        "max_score": null,
        "hits": []
    }
}

ES 环境

#节点 1 的配置信息:
#集群名称,节点之间要保持一致
cluster.name: my-elasticsearch
#节点名称,集群内要唯一
node.name: node-1001
#该节点是否为候选主节点
node.master: true
#该节点是否为候选数据节点
node.data: true
#节点绑定的 ip 地址或主机名
network.host: localhost
#设置存储数据的目录,使用全路径
path.data: /path/to/data
#设置节点的日志目录
path.logs: /path/to/logs
#http 端口,客户端使用的端口,如果在同一个服务器部署多个 es,则需要设置不同的值,多个服务器使用默认 9200 就可以,设置为 -1 表示禁用 http api
http.port: 1001
#tcp 监听端口,节点之间通信的端口
transport.tcp.port: 9301
#其他的节点地址,如何节点默认使用 9300 端口,则可以不写端口
discovery.seed_hosts: ["localhost:9301", "localhost:9302","localhost:9303"]
discovery.zen.fd.ping_timeout: 1m
discovery.zen.fd.ping_retries: 5
#该设置的作用是在执行破坏性操作(例如删除索引)时需要提供名称,用于防止以外操作
action.destructive_requires_name: true
#集群内的可以被选为主节点的节点列表
cluster.initial_master_nodes: ["node-1", "node-2","node-3"]
#跨域配置
http.cors.enabled: true
http.cors.allow-origin: "*"
{
    "cluster_name": "my-application",
    "status": "green",
    "timed_out": false,
    "number_of_nodes": 3,
    "number_of_data_nodes": 3,
    "active_primary_shards": 0,
    "active_shards": 0,
    "relocating_shards": 0,
    "initializing_shards": 0,
    "unassigned_shards": 0,
    "delayed_unassigned_shards": 0,
    "number_of_pending_tasks": 0,
    "number_of_in_flight_fetch": 0,
    "task_max_waiting_in_queue_millis": 0,
    "active_shards_percent_as_number": 100.0
}
  1. 下载:https://www.elastic.co/cn/downloads/past-releases/elasticsearch-7-8-0
  2. 解压:
# 解压缩
tar -zxvf elasticsearch-7.8.0-linux-x86_64.tar.gz -C /opt/module
# 改名
mv elasticsearch-7.8.0 es
  1. 创建用户:因为安全问题, Elasticsearch 不允许 root 用户直接运行,所以要创建新用户,在 root 用户中创建新用户。
useradd es #新增 es 用户
passwd es #为 es 用户设置密码
userdel -r es #如果错了,可以删除再加
chown -R es:es /opt/module/es #文件夹所有者
  1. 修改配置文件
1 /opt/module/es/config/elasticsearch.yml 
# 加入如下配置
cluster.name: elasticsearch
node.name: node-1
network.host: 0.0.0.0
http.port: 9200
cluster.initial_master_nodes: ["node-1"]

2/etc/security/limits.conf
# 在文件末尾中增加下面内容
# 每个进程可以打开的文件数的限制
es soft nofile 65536
es hard nofile 65536

3/etc/security/limits.d/20-nproc.conf
# 在文件末尾中增加下面内容
# 每个进程可以打开的文件数的限制
es soft nofile 65536
es hard nofile 65536
# 操作系统级别对每个用户创建的进程数的限制
* hard nproc 4096
# 注: * 带表 Linux 所有用户名称

4/etc/sysctl.conf
# 在文件中增加下面内容
# 一个进程可以拥有的 VMA(虚拟内存区域)的数量,默认值为 65536
vm.max_map_count=655360

5
sysctl -p
  1. 启动软件,使用 ES 用户启动
cd /opt/module/es/
#启动
bin/elasticsearch
#后台启动
bin/elasticsearch -d  
  1. 关闭防火墙
#暂时关闭防火墙
systemctl stop firewalld
#永久关闭防火墙
systemctl enable firewalld.service #打开防火墙永久性生效,重启后不会复原
systemctl disable firewalld.service #关闭防火墙,永久性生效,重启后不会复原
# 加入如下配置
#集群名称
cluster.name: cluster-es
#节点名称, 每个节点的名称不能重复
node.name: node-1
#ip 地址, 每个节点的地址不能重复
network.host: linux1
#是不是有资格主节点
node.master: true
node.data: true
http.port: 9200
# head 插件需要这打开这两个配置
http.cors.allow-origin: "*"
http.cors.enabled: true
http.max_content_length: 200mb
#es7.x 之后新增的配置,初始化一个新的集群时需要此配置来选举 master
cluster.initial_master_nodes: ["node-1"]
#es7.x 之后新增的配置,节点发现
discovery.seed_hosts: ["linux1:9300","linux2:9300","linux3:9300"]
gateway.recover_after_nodes: 2
network.tcp.keep_alive: true
network.tcp.no_delay: true
transport.tcp.compress: true
#集群内同时启动的数据任务个数,默认是 2 个
cluster.routing.allocation.cluster_concurrent_rebalance: 16
#添加或删除节点及负载均衡时并发恢复的线程个数,默认 4 个
cluster.routing.allocation.node_concurrent_recoveries: 16
#初始化数据恢复时,并发恢复线程的个数,默认 4 个
cluster.routing.allocation.node_initial_primaries_recoveries: 16

进阶概念

💡tip

容易被混淆的概念是:Lucene 索引,我们在 Elasticsearch 称作 分片 。 一个Elasticsearch 索引是分片的集合。 当 Elasticsearch 在索引中搜索的时候, 他发送查询到每一个属于索引的分片(Lucene 索引),然后合并每个分片的结果到一个全局的结果集。

文档分析

{
    "analyzer": "standard",// 标准分词器
    "text": "Text to analyze"
}
{
    "text":"测试单词",
    "analyzer":"ik_max_word" // 会将文本做最细粒度的拆分。
  // 或者 "analyzer":"ik_smart" 会将文本做最粗粒度的拆分。
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <comment>IK Analyzer 扩展配置</comment>
    <!--用户可以在这里配置自己的扩展字典 -->
    <entry key="ext_dict">custom.dic</entry>
     <!--用户可以在这里配置自己的扩展停止词字典-->
    <entry key="ext_stopwords"></entry>
    <!--用户可以在这里配置远程扩展字典 -->
    <!-- <entry key="remote_ext_dict">words_location</entry> -->
    <!--用户可以在这里配置远程扩展停止词字典-->
    <!-- <entry key="remote_ext_stopwords">words_location</entry> -->
</properties>
{
    "text":"测试单词",
    "analyzer":"ik_max_word"
}
{
    "tokens": [
        {
            "token": "弗雷尔卓德", // token 是实际存储到索引中的词条
            "start_offset": 0, // start_ offset 和 end_ offset 指明字符在原始字符串中的位置。
            "end_offset": 5,
            "type": "CN_WORD", // type 指明词条的类型
            "position": 0 // position 指明词条在原始文本中出现的位置。
        }
    ]
}
POST demand/_update_by_query?conflicts=proceed
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "username": "flm"
          }
        }
      ]
    }
  },
  "script": {
    "source": "ctx._source.nickname = params.new_nickname",
    "lang": "painless",
    "params": {
      "new_nickname": "小奇迹"
    }
  }
}
ℹ️note

painless 脚本只对查询出来的文档逐个运行脚本