ES从入门到入土
1.es简介
ES是一个基于Lucene的分布式全文搜索服务器,和SQL Server的全文索引(Fulltext Index)有点类似,都是基于分词和分段的全文搜索引擎,具有分词,同义词,词干查询的功能,但是ES天生具有分布式和实时的属性,
Elasticsearch 的底层是开源库 Lucene。但是,你没法直接用 Lucene,必须自己写代码去调用它的接口。Elastic 是 Lucene 的封装,提供了 REST API 的操作接口,开箱即用。
特点:
- 全文搜索
- 结构化搜索
- 分析
与solr的区别
- Solr 官方提供的功能更多,而 Elasticsearch 本身更注重于核心功能,高级功能多有第三方插件提供;
- Solr 在传统的搜索应用中表现好于 Elasticsearch,但在处理实时搜索应用时效率明显低于 Elasticsearch。
全文搜索(Full-text Search)
全文检索是指计算机索引程序通过扫描文章中的每一个词,对每一个词建立一个索引,指明该词在文章中出现的次数和位置,当用户查询时,检索程序就根据事先建立的索引进行查找,并将查找的结果反馈给用户的检索方式。
在全文搜索的世界中,存在着几个庞大的帝国,也就是主流工具,主要有:
- Apache Lucene
- Elasticsearch
- Solr
- Ferret
**倒排索引(Inverted Index)
该索引表中的每一项都包括一个属性值和具有该属性值的各记录的地址。由于不是由记录来确定属性值,而是由属性值来确定记录的位置,因而称为倒排索引(inverted index)。Elasticsearch能够实现快速、高效的搜索功能,正是基于倒排索引原理。
2.安装es
声明:JDK1.8以上—>最低要求
es客户端暂时使用kibana
在安装Elasticsearch引擎之前,必须安装ES需要的软件环境,安装Java JDK和配置JAVA_HOME环境变量:
略
官网:https://www.elastic.co/cn/elasticsearch/
docker安装:参考 参码踪 https://www.shenmazong.com/blog/1402150382527000576
es+kibana 下载地址:链接:https://pan.baidu.com/s/1Q78F5ClP_hLqsLm1exDCdA
提取码:6tn1
下载后,修改文件jvm.options如下:
-Xms1g
-Xmx1g
运行bin目录下 的 elasticsearch.bat
执行命令
启动 kibana 、bin目录下的kibana.bat 访问 http://localhost:5601
3.javaAPI操作
添加依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.8.1</version>
</dependency>
<!-- 上面是es依赖,下面是测试依赖 ->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
创建索引
CreateIndexRequest request = new CreateIndexRequest("tb_hero");
// 设置索引参数
request.settings(Settings.builder()
.put("index.number_of_shards", 3)
.put("index.number_of_replicas", 2)
);
// 设置映射
Map<String, Object> properties = new HashMap<>();
//-- name
Map<String, Object> name = new HashMap<>();
name.put("type", "text");
properties.put("name", name);
//-- gender
Map<String, Object> gender = new HashMap<>();
gender.put("type", "text");
properties.put("gender", gender);
//-- age
Map<String, Object> age = new HashMap<>();
age.put("type", "integer");
properties.put("age", age);
//-- work
Map<String, Object> work = new HashMap<>();
work.put("type", "text");
properties.put("work", work);
Map<String, Object> mapping = new HashMap<>();
mapping.put("properties", properties);
request.mapping(mapping);
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
client.close();
文档操作
1.新增文档
@Test
public void addDocumentOne() throws IOException {
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("name", "🐎文博");
jsonMap.put("age", 23);
jsonMap.put("gender", "男");
jsonMap.put("work", "码农");
IndexRequest indexRequest = new IndexRequest("tb_hero")
.id("1").source(jsonMap);
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
}
2.修改
@Test
public void updateDocumentOne() throws IOException {
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("name", "牛马");
jsonMap.put("work", "产品经理");
UpdateRequest request = new UpdateRequest("tb_hero", "1")
.doc(jsonMap);
UpdateResponse updateResponse = client.update(
request, RequestOptions.DEFAULT);
}
3.删除
@Test
public void deleteDocument() throws IOException {
// 删除文档
DeleteRequest request = new DeleteRequest("tb_hero","1");
DeleteResponse deleteResponse = client.delete(
request, RequestOptions.DEFAULT);
// 检查删除结果
GetRequest getRequest = new GetRequest("tb_hero","1");
// Disable fetching _source.
getRequest.fetchSourceContext(new FetchSourceContext(false));
// Disable fetching stored fields.
getRequest.storedFields("_none_");
boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
System.out.println(exists);
}
4.SpringBoot 集成 es
1.导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
2.配置yml
学习默认不配置
配置文件 : https://blog.csdn.net/lukabruce/article/details/104814214
3.CRUD
创建实体类
package com.baidu.dto;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* @description TODO
* @author -还怕大雨吗
* @date 2021/7/9 15:05
* @version 1.0
*/
//索引的名称,再次加注解后,若没有索引自动创建
@Document(indexName = "tb_user")
public class Users {
//设置为id
@Id
private Integer id;
@Field(type = FieldType.Keyword)
private String name;
@Field(type = FieldType.Text,analyzer = "ik_smart")
private String pwd;
@Field(type = FieldType.Text,analyzer = "ik_smart")
private String messages;
}
注入模板
->>>> spring Boot 集成 es 所创建的模板
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
新增
@PostMapping("add")
public void add(){
Users users = new Users();
users.setId(1);
users.setName("🐎文博");
users.setPwd("123");
users.setMessages("吃饭");
elasticsearchRestTemplate.save(users);
}
//数据自拟
查询单个
@PostMapping("findByid")
public Users find(Integer id){
//id需要转换string
Users u = elasticsearchRestTemplate.get(id.toString(),Users.class);
return u;
}
修改
@PostMapping("update")
public void update(Users users){
//es的修改比较麻烦,使用这种覆盖的方式
Users users1 = elasticsearchRestTemplate.get(users.getId().toString(), Users.class);
users1.setName("牛马");
users1.setPwd("111");
users1.setMessages("修改");
elasticsearchRestTemplate.save(users1);
}
根据id删除
@PostMapping("delet")
public void delet(Integer id){
// elasticsearchRestTemplate.delete("实体类对象")
elasticsearchRestTemplate.delete(id.toString(),Users.class);
}
不分词查询
@PostMapping("term")
public List<Users> term(){
List<Users> list = new ArrayList<>();
NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
不分词查询 参数1: 字段名,参数2:字段查询值,因为不分词,所以汉字只能查询一个字,英语是一个单词.
NativeSearchQuery build = builder.withQuery(QueryBuilders.termQuery("name", "赵")).build();
//term是不分词查询
// NativeSearchQuery build = builder.withQuery(QueryBuilders.termsQuery("name", "马","牛","鸭")).build();
SearchHits<Users> search = elasticsearchRestTemplate.search(build, Users.class);
List<SearchHit<Users>> searchHits = search.getSearchHits();
for (SearchHit<Users> searchHit : searchHits) {
list.add(searchHit.getContent());
}
return list;
}
分词查询
@PostMapping("mult")
public List<Users> mult(){
List<Users> list = new ArrayList<>();
NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
//根据参数1 , 查询后面的多个字段,,如果有数据就返回
NativeSearchQuery build = builder.withQuery(QueryBuilders.multiMatchQuery("鬼子", "messages","name","age")).build();
//匹配所有文件,相当于就没有设置查询条件
// NativeSearchQuery build = builder.withQuery(QueryBuilders.matchQuery("鬼", "messages")).build();
SearchHits<Users> search = elasticsearchRestTemplate.search(build, Users.class);
List<SearchHit<Users>> searchHits = search.getSearchHits();
for (SearchHit<Users> searchHit : searchHits) {
list.add(searchHit.getContent());
}
return list;
}
5.kibana操作
查询所有索引->>>>> GET _cat/indices?v
查询改索引里的所有文档 ->>> GET tb_user/_search
查询单个 ->>>> GET /tb_user/_doc/17
查询索引结构 ->>> GET tb_user
删除索引 ->>> DELETE tb_user
根据id删除 ->>> DELETE /tb_user/_doc/id