一、安装
1、docker 安装
版本以官网为准,因为是7.x版本开始才支持的docker部署
java开发、基于restful接口的分布式、高拓展、高实时的搜索与数据分析引擎
基于lucene的搜索服务器
应用
搜索:海量数据库
日志数据分析
实时数据分析
拉取
docker pull elasticsearch:7.12.1
docker pull kibana:7.12.1
配置
mkdir -p /mydata/elasticsearch/config
mkdir -p /mydata/elasticsearch/data
echo "http.host: 0.0.0.0" >/mydata/elasticsearch/config/elasticsearch.yml
chmod -R 777 /mydata/elasticsearch/
启动elasticsearch
docker run --name elasticsearch -itd -p 9200:9200 -p 9300:9300 -v 你的目录:/usr/share/elasticsearch/data -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:7.12.1
添加ik分词器
docker cp ik elasticsearch:/usr/share/elasticsearch/plugins
启动kibana
docker run --name kibana -d --link(添加链接到另一个容器) elasticsearch:elasticsearch -p 5601:5601 kibana:7.12.1
二、kibana操作
- 切换中文
在config/kibana.yml添加
i18n.locale: "zh-CN"
1、操作索引
1、创建索引
PUT /library/
{
"settings":{
"index":{
"number_of_shards":3,
"number_of_replicas":0
}
}
}
索引的名称为lib
number_of_shards:分片的数量为3,分片的数量一旦确定了就不能修改
number_of_replicas: 备份的数量为1,由于就1台服务器因此备份数量为0
直接创建一个索引,会使用默认配置
PUT lib2
2、查看索引
查看所有索引的配置
GET _all/_settings
# 查看所有节点
GET _cat/nodes
# 查看素有索引
GET _all
GET /library
3、删除索引
DELETE /library
4、更新索引(打开,关闭,更新)
关闭索引
POST /library/_close
2、添加映射
映射类型
1、字符串
text: 会分词,不支持聚合
keyword: 不会分词,将全部内容作为一个词条,支持聚合
创建索引
PUT /person
创建映射
PUT /person/_mapping
{
"properties":{
"name":{
"type":"keyword"
},
"age":{
"type":"integer"
},
"adress":{
"type":"keyword"
}
}
}
查询映射
GET /person/_mapping
创建索引并添加映射
PUT /person
{
"mappings":{
"properties": {
"name":{
"type":"keyword"
},
"age":{
"type":"integer"
},
"adress":{
"type":"keyword"
}
}
}
}
添加字段
PUT /person/_mapping
{
"properties":{
"birthday":{
"type":"text"
}
}
}
3、操作文档
1、查讯所有文档
GET /library/book/_search
2、添加文档
PUT /person/_doc/2
{
"name":"瑶池",
"age":25,
"adress":"东荒",
"birthday":"1996-05-19"
}
2、
三、ElasticSearch
1、注意
root用户不能直接运行
2、ik分词器
es 默认分词器为standard ,需要修改为ik分词器
粗粒度分词
GET /_analyze
{
"analyzer": "ik_max_word",
"text":"春风又绿江南岸"
}
细粒度分词
GET /_analyze
{
"analyzer": "ik_smart",
"text":"春风又绿江南岸"
}
3、使用
创建索引,添加映射,并制定分词器
PUT /person
{
"mappings": {
"properties": {
"name":{
"type":"text",
"analyzer": "ik_smart"
},
"age":{
"type":"integer"
},
"adress":{
"type":"text",
"analyzer": "ik_max_word"
}
}
}
}
查询
GET /person/_search
{
"query": {
"term": {
"name": {
"value": "凝霜"
}
}
}
}
批量操作
bulk
POST /person/_bulk
{"create":{"_index":"person","_id":"2"}}
{"name":"楚萱儿","age":"18","adress":"昆仑"}
{"update":{"_index":"person","name":"2"}}
{"doc":{"name":"楚灵儿"}}
4、java API操作
坐标
<!--引入es的坐标-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.12.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.12.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.12.1</version>
</dependency>
4.1 配置
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ElasticSeachConfig {
private String host;
private int port;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
@Bean
public RestHighLevelClient client() {
return new RestHighLevelClient(RestClient.builder(
new HttpHost(
host,
port,
"http"
)
));
}
}
4.2 索引操作
@org.junit.Test
public void testCreateIndice() throws IOException {
CreateIndexRequest createIndexRequest = new CreateIndexRequest("user");
Map<String, Object> message1= new HashMap<>();
message1.put("type","integer");
Map<String, Object> message2= new HashMap<>();
message2.put("type","text");
Map<String, Object> message3= new HashMap<>();
message3.put("type","text");
Map<String, Object> message4= new HashMap<>();
message4.put("type","text");
Map<String, Object> properties = new HashMap<>();
properties.put("id",message1);
properties.put("username",message2);
properties.put("password",message3);
properties.put("mobile",message4);
Map<String, Object> mapping= new HashMap<>();
mapping.put("properties",properties);
createIndexRequest.mapping(mapping);
CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
String index = createIndexResponse.index();
System.out.println(index);
}
@org.junit.Test
public void getAllIndex() throws IOException {
//获取索引
GetIndexRequest getIndexRequest = new GetIndexRequest("_all");
GetIndexResponse response = client.indices().get(getIndexRequest, RequestOptions.DEFAULT);
String[] indices = response.getIndices();
for (String index : indices) {
System.out.println(index);
}
}
4.3 批量操作
@Test
public void testBulk() throws IOException {
//创建bulk对象
BulkRequest bulkRequest = new BulkRequest();
//添加操作
Map map = new HashMap();
map.put("name","黄蓉");
map.put("age","23");
map.put("adress","桃花岛");
IndexRequest indexRequest = new IndexRequest("person").id("4").source(map);
bulkRequest.add(indexRequest);
//修改操作
Map map1 = new HashMap();
map1.put("name","凝霜");
UpdateRequest updateRequest = new UpdateRequest("person","LuiRxXkB0rYXJy3I_ViE")
.doc(map1);
bulkRequest.add(updateRequest);
BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
RestStatus status = response.status();
System.out.println(status);
System.out.println(status.getStatus());
}
3、导入数据
//es导入数据
@Test
public void importData() throws IOException {
//查询数据
PageInfo<Person> pageInfo = personService.findAll(1, 30);
List<Person> personList = pageInfo.getList();
//bulk导入
BulkRequest bulkRequest = new BulkRequest();
//循环list,创建IndexRequest,导入数据
for (Person person : personList) {
IndexRequest indexRequest = new IndexRequest("person");
indexRequest.id(Integer.toString(person.getId()));
indexRequest.source(objectMapper.writeValueAsString(person), XContentType.JSON);
bulkRequest.add(indexRequest);
}
BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(response);
}
4、查询数据
/**
* 查询操作
* 1、matchAll
* 2、将查询结果封装
* 3、分页,默认显示10条
*/
@Test
public void find() throws IOException {
//2. 构建查询请求对象,,指定查询的索引名称
SearchRequest searchRequest = new SearchRequest("person");
//4.创建查询条件构造器
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//6. 查询条件
QueryBuilder query = QueryBuilders.matchAllQuery();//查询所有文档
//5. 指定查询条件
sourceBuilder.query(query);
//8. 分页条件
sourceBuilder.from(0);
sourceBuilder.size(4);
//3. 添加查询条件构建器
searchRequest.source(sourceBuilder);
//1. 查询,获取查询结果
SearchResponse response = client.search(searchRequest,RequestOptions.DEFAULT);
//7. 获取命中对象
SearchHits searchHits = response.getHits();
//获取记录数
long value = searchHits.getTotalHits().value;
System.out.println("总记录数:"+value);
//获取数据,数组
SearchHit[] hits = searchHits.getHits();
for (SearchHit hit : hits) {
//获取json格式的数据
String json = hit.getSourceAsString();
//转为java对象
Person person = objectMapper.readValue(json, Person.class);
System.out.println(person);
}
}
- 查询分类
1. matchAll: 查询所有,默认一次展示10条数据
GET /person/_search
{
"query": {
"match_all": {}
},
"from":0,
"size":4
}
2. term查询:不会对词条进行分词
3. match: 会对词条进行分词,并去并集
4. 模糊查询:
wildcard查询 会对查询条件进行分词,可以使用通配符 ? *
regexp查询 正则查询
prefix查询 前缀查询,对keyword词条比较友好
5. 范围查询: range
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
//执行上限
rangeQuery.lte(20);
//指定下限
rangeQuery.gte(1);
sourceBuilder.sort("age", SortOrder.DESC
);
6. queryString查询:
会对查询条件进行分词
然后将分词的查询条件和词条进行等值匹配
默认取并集
可以指定多个查询字段
QueryBuilders.queryStringQuery()
7. 布尔查询: boolQuery,对多个查询条件连接,
连接方式
must 条件必须城里
must_not 条件必须不成立
should 条件可以成立
filter 条件必须成立,性能比must高,不会计算得分
8. 聚合查询
指标聚合 相当于mysql的聚合函数,max,min,avg,sum
桶聚合 相当于mysql的groupby,不要对text类型的数据进行分组,会失败
9. 高亮查询:
10. 重建索引
es索引一旦创建,只允许添加字段,不允许改变字段。因为改变字段,需要重建倒排索引,影响内存结构,性能太低
重建一个新索引,并将原有的数据导入到新索引
改代码
POST _reindex
{
"source": {
"index": ""
},
"dest": {
"index": ""
}
}
索引别名
POST /person/_alias/person_v1
四、ElasticSearch集群
1、集群搭建
es天然支持集群
es的设计隐藏了分布式本身的复杂性
集群:一组拥有共同的cluster name的节点
节点:集群中的一个es实例
索引:es存储数据的地方,相当于mysql的database
分片:索引可以被拆分为不同的部分进行存储,成为分片,在集群环境下,一个索引的不同分片可以拆分到不同的节点中
主分片:
副本分片:
2、java操作集群
@Bean
public RestHighLevelClient client() {
return new RestHighLevelClient(RestClient.builder(
new HttpHost(
host,
port,
"http"
),
new HttpHost(
host,
port,
"http"
),
new HttpHost(
host,
port,
"http"
)
));
}
3、分片管理
在创建索引不指定分片时,默认主分片1,副分片1