elasticsearch学习
什么是elasticsearch?
1、是一种面向文档的搜索引擎与数据分析,他能根据value 获取到key (倒排索引) ,能够根据搜索关键字搜索到想要查到的内容。
elasticsearch 与传统数据库对应关系
elasticsearch | MySQL |
---|---|
index | database |
type | table |
Document | Row |
Field | Columns |
mappings | 每个列的约束 |
基本操作命令
ik分词器
查看分析信息请求
GET _analyze
{
“analyzer”: “ik_smart”,
“text”: “我是真爱坤”
}
GET _analyze
{
“analyzer”: “ik_max_word”,
“text”: “我是真爱坤”
}
操作概览
method | url地址 | 描述 |
---|---|---|
PUT | localhost:9200/索引名称/类型名称/文档id | 创建文档{指定文档id} |
POST | localhost:9200/索引名称/类型名称 | 创建文档{随机文档id} |
POST | localhost:9200/索引名称/类型名称/文档id/_update | 更新文档 |
DELETE | localhost:9200/索引名称/类型名称/文档id | 删除文档 |
GET | localhost:9200/索引名称/类型名称/文档id | 根据id查询文档 |
GET | localhost:9200/索引名称/类型名称/_search | 查询所有数据 |
创建索引
PUT /索引名称/类型名称/id 其中 类型名称会被弃用
{请求体}
PUT /test/user/2
{
“name”:“liangshiliang”
}
创建索引 自定义规则
PUT /索引名
{
“settings” { //此为索引的一些设置
“number_of_replicas”: 1, // 副本个数
“number_of_shards”: 1 // 分片数
},
“mappings”: { // 字段映射
“properties”:{} //属性设置 可以设置字段名称和类型
}
}
创建索引 自定义规则Demo
PUT /test2
{
“settings”: {
“number_of_replicas”: 1,
“number_of_shards”: 1
},
“mappings”: {
“properties”: {
“name”: {
“type”: “text”
},
“age”:{
“type”: “long”
}
}
}
}
查看索引信息
GET /索引名称
向索引内插入数据
PUT /索引名/索引id
由于我们创建索引的时候,没有给type所以默认的type为_doc,elasticsearch 7.x 以上只支持一个索引对应一个type 所以这就是后面为什么要废除type类型。如果我PUT 中id不变,重新执行,会变为更新,此更新为完全覆盖。
使用post更新
POST /索引名称/字段类型/文档id/_update
{
“doc”: {
// 更新内容
}
}
更新demo
删除操作 delete 后面无文档,则删除整个索引
对文档的具体查询
类型为keywork的字段不会被分词器解析
GET 请求查询
GET /索引名/类型名称/_search
参数名称 | 父字段 | 描述 |
---|---|---|
query | 对文档进行条件查询 | |
match | query/ must/must_not/should | query的子字段,里面写需要查询的条件与SQL的where相似,text类型的字段为模糊查询为单条件查询,使用分词器进行分词查询,如想要改字段多个内容,空格后追加内容 列子 ”蔡徐坤 成龙“ |
term | query/ must/must_not/should | query的子字段,此为根据分词器进行匹配,并且为精确匹配 |
bool | query | query的子字段,里面写需要查询的条件与SQL的where相似,可以写多条件查询 |
must | bool | 此为&条件,类型为对象数组,条件都必须满足,数组里面有多少个对象就有多少个条件 ,类似SQL的where and条件 |
must_not | bool | 此为不等于条件,类型为对象数组,数组里面有多少个对象就有多少个条件 ,类似SQL的where ! 或<>条件 |
should | bool | 此为|条件,类型为对象数组,条件其中一个满足,则满足,数组里面有多少个对象就有多少个条件 ,类似SQL的where or条件 |
filter | bool | 可以过滤条件,范围性的过滤 |
sort | 条件排序,数组类型 | |
_source | 自定义返回字段,数组类型 |
查询Demo 样例
整合Spring Boot项目
Maven 引用
这里版本号是根据引用的父工程相关的。所以没有写版本号 需要注意elasticsearch 版本要与所要连接的版本一致,如果不一致,则需要更改版本号
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
版本不一致时更改方法
1、更改父工程引用的版本号
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<elasticsearch.version>7.6.1</elasticsearch.version>
</properties>
2、重新导入自己需要的版本jar,我的版本号均为7.6.1
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>transport-netty4-client</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.6.1</version>
</dependency>
使用config配置类注入客户端,或者用xml 都可以。
elasticsearch 各类汇总
类名 | 作用 |
---|---|
CreateIndexRequest | 创建索引类 |
GetIndexRequest | 获取索引类 |
DeleteIndexRequest | 删除索引类 |
AcknowledgedResponse | 删除索引返回类,isAcknowledged ,true为删除成功 |
IndexRequest | 向索引插入数据 |
GetRequest | 根据id查询数据 |
SearchRequest | 查询类可复杂查询 |
SearchSourceBuilder | 构建查询条件,与SearchRequest配套使用,可以设置一些分页大小等信息 |
BoolQueryBuilder | 具体查询条件,可以使用must/mustnot/should/filter |
MatchQueryBuilder | must/mustnot/should 的入参 |
TermQueryBuilder | must/mustnot/should 的入参 |
java测试
索引创建
如果运行时报错,需要看看自己的maven导入的jar版本是否是一致
若版本不一致则会出现
Failed to instantiate [org.elasticsearch.client.RestHighLevelClient]: Factory method 'restHighLevelClient' threw exception; nested exception is java.lang.NoClassDefFoundError: org/elasticsearch/action/admin/cluster/repositories/cleanup/CleanupRepositoryRequest
Invocation of init method failed; nested exception is java.lang.IncompatibleClassChangeError: Found class org.elasticsearch.common.bytes.BytesReference, but interface was expected
这就是因为版本不一致导致
具体操作demo
package com.lsl.movie.elk.test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.gson.JsonObject;
import com.lsl.movie.elk.model.User;
import com.sun.org.apache.xpath.internal.SourceTree;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@SpringBootTest
public class ElasticTest {
@Resource
private RestHighLevelClient client;
/**
* 创建索引
*/
@Test
public void testIndex(){
// 创建索引请求
CreateIndexRequest indexAction = new CreateIndexRequest("test_index3");
// 执行请求
try {
CreateIndexResponse createIndexResponse = client.indices().create(indexAction, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(createIndexResponse, SerializerFeature.IgnoreErrorGetter));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除索引
*/
@Test
public void testDeleteIndex(){
// 创建索引请求
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("test_index3");
// 执行请求
try {
AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(delete, SerializerFeature.IgnoreErrorGetter));
boolean acknowledged = delete.isAcknowledged();
System.out.println(acknowledged);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 单条插入
*/
@Test
public void testDocument(){
// 插入数据
IndexRequest indexRequest = new IndexRequest("test_index2");
User user = new User("13","蔡徐坤","爱打篮球");
// 将数据插入source 中
indexRequest.source(JSONObject.toJSONString(user), XContentType.JSON);
indexRequest.id("2");
IndexResponse index = null;
try {
index = client.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(index);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 根据id查询文档
*/
@Test
public void getDocument(){
// 插入数据
GetRequest getRequest = new GetRequest("test_index2","18");
// 将数据插入source 中
try {
GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);
System.out.println(JSONObject.toJSONString(documentFields));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 批量插入
*/
@Test
public void insertBatchDocument(){
// 插入数据
BulkRequest bulkRequest = new BulkRequest("test_index2");
for (int i = 0; i < 10; i++) {
User user = new User("13"+i,"杨大明星"+i,"爱打篮球");
bulkRequest.add(new IndexRequest().source(JSONObject.toJSONString(user),XContentType.JSON).id((i+10)+""));
}
try {
BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(JSONObject.toJSONString(bulk));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 查询条件
*/
@Test
public void testSearch(){
// 查询数据
SearchRequest request = new SearchRequest("test_index2");
// 查询构造器
SearchSourceBuilder builder = new SearchSourceBuilder();
boolean must = false;
try {
builder.query(new MatchQueryBuilder("name","蔡"));
builder.size(20);
request.source(builder);
SearchResponse search = client.search(request, RequestOptions.DEFAULT);
System.out.println(search);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(must);
}
/**
* 复杂查询条件
*/
@Test
public void testSearch2(){
// 查询数据
SearchRequest request = new SearchRequest("test_index2");
// 查询构造器
SearchSourceBuilder builder = new SearchSourceBuilder();
boolean must = false;
try {
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().must(new MatchQueryBuilder("name", "杨"))
.mustNot(new TermQueryBuilder("id", "134 135"));
builder.query(queryBuilder);
builder.size(20);
request.source(builder);
SearchResponse search = client.search(request, RequestOptions.DEFAULT);
System.out.println(search);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(must);
}
}