简介
Elasticsearch 是一个实时的分布式搜索分析引擎,它能让你以前所未有的速度和规模,去探索你的数据。
安装
下载
# 下载
wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.5.1.tar.gz
# 解压
tar zxvf elasticsearch-6.5.1.tar.gz
添加用户
es不能使用root用户启动,这里添加一个新用户
# 添加用户
useradd es
# 给es用户分权限
chown -R es ./elasticsearch-6.5.1
修改jvm内存
jvm默认使用的是1g内存,需要根据自己的环境内存修改
vim elasticsearch-6.5.1/config/jvm.options
以下两个数值根据自己的内存修改,由于我的环境内存只有1g,因此只能设置小一点了
-Xms500m
-Xmx500m
修改es相关配置
vim elasticsearch-6.5.1/config/elasticsearch.yml
单机配置
单机的话修改一下host可以外网访问,其它的采用默认配置即可,默认监听端口9200
# 绑定ip 0.0.0.0支持外网访问
network.host: 0.0.0.0
多节点配置
master节点配置
# 设置集群名称
cluster.name: gift
# 设置节点名称,每个节点名称唯一
node.name: master
# 设置为master节点
node.master: true
# 绑定ip 0.0.0.0支持外网访问
network.host: 0.0.0.0
# 绑定端口
http.port: 9200
# 支持跨域访问
http.cors.enabled: true
http.cors.allow-origin: "*"
slave节点配置
# 设置集群名称
cluster.name: gift
# 设置节点名称,每个节点名称唯一
node.name: slave1
# 绑定ip 0.0.0.0支持外网访问
network.host: 0.0.0.0
# 绑定端口
http.port: 9201
# 集群发现,添加master节点ip
discovery.zen.ping.unicast.hosts: ["192.168.1.1"]
# 支持跨域访问
http.cors.enabled: true
http.cors.allow-origin: "*"
启动
# 前台启动
/elasticsearch-6.5.1/bin/elasticsearch
# 后台启动
/elasticsearch-6.5.1/bin/elasticsearch -d
浏览器访问
浏览器访问 ip:9200,出现类似如下的信息则启动成功
{
"name" : "9Y53rnH",
"cluster_name" : "elasticsearch",
"cluster_uuid" : "J2tZvMqEQ-mkwIYP5zf21g",
"version" : {
"number" : "6.5.1",
"build_flavor" : "default",
"build_type" : "tar",
"build_hash" : "8c58350",
"build_date" : "2018-11-16T02:22:42.182257Z",
"build_snapshot" : false,
"lucene_version" : "7.5.0",
"minimum_wire_compatibility_version" : "5.6.0",
"minimum_index_compatibility_version" : "5.0.0"
},
"tagline" : "You Know, for Search"
}
索引
分片数:节点数的1.5-3倍,注意是整型,索引创建后不能修改,默认5
副本数:索引创建后可以修改,默认1
结构化
创建索引并结构化
mapping一旦创建字段就不允许修改,但是可以添加新的字段
示例如下:
PUT /my_index
请求:
{
"mappings": {
"video": {
"properties": {
"name": {
"type": "text"
},
"cat_id": {
"type": "integer"
},
"type": {
"type": "byte"
},
"uploader": {
"type": "keyword"
}
}
}
}
}
返回:
{
"acknowledged": true,
"shards_acknowledged": true,
"index": "imooc_video"
}
添加新的字段
给指定的type添加新的mapping字段
PUT /my_index/_mapping/my_type
{
"properties": {
"status": {
"type": "byte"
},
"video_id": {
"type": "byte"
}
}
}
返回:
{
"acknowledged": true
}
查看索引
GET /my_index
文档操作
添加
自己指定id,如果id存在则修改,如果不存在则新增
PUT /my_index/my_type/指定的ID
{
"name": "刘德华",
"content": "我是刘德华呀",
"image": "https://www.baidu.com/a.png",
"url": "https://wwewe.com/m.mp4",
"type": 1,
"uploader": "sinsfa",
"status": 1,
"video_id": 1
}
es自动生成ID
POST /my_index/my_type
{
"name": "刘德华1",
"content": "我是刘德华呀",
"image": "https://www.baidu.com/a.png",
"url": "https://wwewe.com/m.mp4",
"type": 1,
"uploader": "sinsfa",
"status": 1,
"video_id": 1
}
搜索
普通查询
match 分词查询
match_phrase 完整词查询
POST /my_index/my_type
{
"query": {
"match" {
"name": "刘德华"
}
}
}
聚合查询
聚合查询类似于Mysql中的select count(*) as count from video group by video_id
PUT /my_idnex/my_type
{
"aggs": {
"my_key": { // 这个字段可以自己定义名称
"terms" {
"field" "video_id"
}
}
}
}