List<Stu> stuList = new ArrayList<>();
stuList.add(stu1);
stuList.add(stu2);
esTemplate.save(stuList);
}
#### 2.5 根据文档id删除数据
@Test
public void deleteDoc(){
esTemplate.delete("10010", Stu.class);
}
#### 2.6 查询文档数据
@Test
public void getDoc(){
System.out.println(esTemplate.get("10011", Stu.class));
}
#### 2.7 修改文档数据
@Test
public void updateDoc(){
Map<String, Object> stuMap = new HashMap<>();
stuMap.put("name", "秦王嬴政");
stuMap.put("age", 2000);
Document doc = Document.from(stuMap);
UpdateQuery updateQuery = UpdateQuery.builder("10011")
.withDocument(doc)
.build();
IndexCoordinates indexCoordinate = IndexCoordinates.of("stu");
esTemplate.update(updateQuery, indexCoordinate);
}
#### 2.8 搜索数据
/**
* 搜索数据
*/
@Test
public void searchStu(){
Pageable pageable = PageRequest.of(0, 10);
SortBuilder sortBuilder = new FieldSortBuilder("money")
.order(SortOrder.ASC);
SortBuilder sortBuilderName = new FieldSortBuilder("name.keyword") # name 有两种类型:text和keyword,其中name.keyword是指其为keyword类型的字段
.order(SortOrder.DESC);
NativeSearchQuery query =new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchQuery("name", "美丽 漂亮"))
.withPageable(pageable)
.withSort(sortBuilder)
.withSort(sortBuilderName)
.build();
SearchHits<Stu> hits = esTemplate.search(query, Stu.class);
System.out.println(hits.getSearchHits());
}
#### 2.9 高亮搜索
@Test
public void highlight(){
String preTag = "<font color='red'>";
String postTag = "</font>";
NativeSearchQuery query = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchQuery("name", "美丽可爱"))
.withHighlightFields(new HighlightBuilder.Field("name")
.preTags(preTag)
.postTags(postTag))
.build();
SearchHits<Stu> hits = esTemplate.search(query, Stu.class);
List<SearchHit<Stu>> stuHits = hits.getSearchHits();
List<Stu> hlList = new ArrayList<>();
for(SearchHit<Stu> h : stuHits){
List<String> hlField = h.getHighlightField("name");
String hlValue = hlField.get(0);
Stu content = h.getContent();
content.setName(hlValue);
hlList.add(content);
}
System.out.println(hlList);
}
## 三、基于Java的Elasticsearch增删改查(Elasticsearch Repositories方式)
#### 1. 创建实体类
@Document(indexName = “stu”, shards = 3, replicas = 0)
public class Stu {
@Id
private Long stuId;
@Field(store = true, analyzer = "ik_max_word", type = FieldType.Text)
private String name;
@Field(store = true, type = FieldType.Integer)
private Integer age;
@Field
private Float money;
@Field
private boolean isMarried;
// getter、setter、toString() 省略
}
#### 2. 创建 mapper 层
/**
- @Author: liuss
- @DateTime: 2023-04-22 13:34
- @Description:
- ElasticsearchRepository<T, ID> T:实体类泛型,ID:ES库中索引的主键类型
*/
public interface StuMapper extends ElasticsearchRepository<Stu, String> {
}
#### 3. 增删改查
3.1 ElasticsearchRepository本身自带了一些简单curd方法,如下图
![](https://img-blog.csdnimg.cn/ec618aac43f74ad3bc042e25fb0d7c0e.png)
使用es自带的方法:
@Test
public void searchStu2(){
Optional<Stu> stu = stuMapper.findById("10021");
Iterable<Stu> stu2 = stuMapper.findAll();
System.out.println(stu);
System.out.println(stu2);
}
3.2 使用自定义的方法
ES在方法名中支持的关键字
| Keyword | Sample | Elasticsearch Query String |
| --- | --- | --- |
| `And` | `findByNameAndPrice` | `{ "query" : { "bool" : { "must" : [ { "query_string" : { "query" : "?", "fields" : [ "name" ] } }, { "query_string" : { "query" : "?", "fields" : [ "price" ] } } ] } }}` |
| `Or` | `findByNameOrPrice` | `{ "query" : { "bool" : { "should" : [ { "query_string" : { "query" : "?", "fields" : [ "name" ] } }, { "query_string" : { "query" : "?", "fields" : [ "price" ] } } ] } }}` |
| `Is` | `findByName` | `{ "query" : { "bool" : { "must" : [ { "query_string" : { "query" : "?", "fields" : [ "name" ] } } ] } }}` |
| `Not` | `findByNameNot` | `{ "query" : { "bool" : { "must_not" : [ { "query_string" : { "query" : "?", "fields" : [ "name" ] } } ] } }}` |
| `Between` | `findByPriceBetween` | `{ "query" : { "bool" : { "must" : [ {"range" : {"price" : {"from" : ?, "to" : ?, "include_lower" : true, "include_upper" : true } } } ] } }}` |
| `LessThan` | `findByPriceLessThan` | `{ "query" : { "bool" : { "must" : [ {"range" : {"price" : {"from" : null, "to" : ?, "include_lower" : true, "include_upper" : false } } } ] } }}` |
| `LessThanEqual` | `findByPriceLessThanEqual` | `{ "query" : { "bool" : { "must" : [ {"range" : {"price" : {"from" : null, "to" : ?, "include_lower" : true, "include_upper" : true } } } ] } }}` |
| `GreaterThan` | `findByPriceGreaterThan` | `{ "query" : { "bool" : { "must" : [ {"range" : {"price" : {"from" : ?, "to" : null, "include_lower" : false, "include_upper" : true } } } ] } }}` |
| `GreaterThanEqual` | `findByPriceGreaterThan` | `{ "query" : { "bool" : { "must" : [ {"range" : {"price" : {"from" : ?, "to" : null, "include_lower" : true, "include_upper" : true } } } ] } }}` |
| `Before` | `findByPriceBefore` | `{ "query" : { "bool" : { "must" : [ {"range" : {"price" : {"from" : null, "to" : ?, "include_lower" : true, "include_upper" : true } } } ] } }}` |
| `After` | `findByPriceAfter` | `{ "query" : { "bool" : { "must" : [ {"range" : {"price" : {"from" : ?, "to" : null, "include_lower" : true, "include_upper" : true } } } ] } }}` |
| `Like` | `findByNameLike` | `{ "query" : { "bool" : { "must" : [ { "query_string" : { "query" : "?*", "fields" : [ "name" ] }, "analyze_wildcard": true } ] } }}` |
| `StartingWith` | `findByNameStartingWith` | `{ "query" : { "bool" : { "must" : [ { "query_string" : { "query" : "?*", "fields" : [ "name" ] }, "analyze_wildcard": true } ] } }}` |
| `EndingWith` | `findByNameEndingWith` | `{ "query" : { "bool" : { "must" : [ { "query_string" : { "query" : "*?", "fields" : [ "name" ] }, "analyze_wildcard": true } ] } }}` |
| `Contains/Containing` | `findByNameContaining` | `{ "query" : { "bool" : { "must" : [ { "query_string" : { "query" : "*?*", "fields" : [ "name" ] }, "analyze_wildcard": true } ] } }}` |
| `In` (when annotated as FieldType.Keyword) | `findByNameIn(Collection<String>names)` | `{ "query" : { "bool" : { "must" : [ {"bool" : {"must" : [ {"terms" : {"name" : ["?","?"]}} ] } } ] } }}` |
| `In` | `findByNameIn(Collection<String>names)` | `{ "query": {"bool": {"must": [{"query_string":{"query": "\"?\" \"?\"", "fields": ["name"]}}]}}}` |
| `NotIn` (when annotated as FieldType.Keyword) | `findByNameNotIn(Collection<String>names)` | `{ "query" : { "bool" : { "must" : [ {"bool" : {"must_not" : [ {"terms" : {"name" : ["?","?"]}} ] } } ] } }}` |
| `NotIn` | `findByNameNotIn(Collection<String>names)` | `{"query": {"bool": {"must": [{"query_string": {"query": "NOT(\"?\" \"?\")", "fields": ["name"]}}]}}}` |
| `Near` | `findByStoreNear` | `Not Supported Yet !` |
| `True` | `findByAvailableTrue` | `{ "query" : { "bool" : { "must" : [ { "query_string" : { "query" : "true", "fields" : [ "available" ] } } ] } }}` |
| `False` | `findByAvailableFalse` | `{ "query" : { "bool" : { "must" : [ { "query_string" : { "query" : "false", "fields" : [ "available" ] } } ] } }}` |
| `OrderBy` | `findByAvailableTrueOrderByNameDesc` | `{ "query" : { "bool" : { "must" : [ { "query_string" : { "query" : "true", "fields" : [ "available" ] } } ] } }, "sort":[{"name":{"order":"desc"}}] }` |
可以自定义方法如下:
public interface StuMapper extends ElasticsearchRepository<Stu, String> {
List<Stu> findStusByName(String name);
}
使用自定义方法查询:
@Test
public void searchStu3(){
List<Stu> stus = stuMapper.findStusByName("didiok");
System.out.println(stus);
}
>
> 这只是其中一部分,更多内容可以参照官方文档:[Spring Data Elasticsearch]( )
>
>
>
## 完整代码如下:
package com.test;
import java.util.*;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.GsonJsonParser;
import org.springframework.boot.json.JsonParser;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.test.context.junit4.SpringRunner;
import com.didiok.Application;
import com.didiok.es.mapper.StuMapper;
import com.didiok.es.pojo.Stu;
import com.didiok.utils.JsonUtils;
/**
-
@Author: liuss
-
@DateTime: 2023-04-21 16:47
-
@Description:
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class ESTest {@Autowired
private ElasticsearchRestTemplate esTemplate;/**
- 创建索引
*/
@Test
public void createIndex(){
esTemplate.indexOps(Stu.class).create();
}
/**
- 删除索引
*/
@Test
public void deleteIndex() {
esTemplate.indexOps(Stu.class).delete();
}
/**
- 判断索引是否存在
*/
@Test
public void existIndex() {
boolean isExist = esTemplate.indexOps(Stu.class).exists();
System.out.println(isExist);
}
/**
-
新增文档数据
*/
@Test
public void addDoc() {Stu stu0 = new Stu(10010L, “didiok”, 18, 100.5f, true);
esTemplate.save(stu0);Stu stu1 = new Stu(10011L, “Rede”, 20, 88.5f, true);
Stu stu2 = new Stu(10012L, “放下”, 22, 108.5f, false);List stuList = new ArrayList<>();
stuList.add(stu1);
stuList.add(stu2);
esTemplate.save(stuList);
}
/**
- 根据文档id删除数据
*/
@Test
public void deleteDoc(){
esTemplate.delete(“10010”, Stu.class);
}
/**
- 查询文档数据
*/
@Test
public void getDoc(){
System.out.println(esTemplate.get(“10011”, Stu.class));
}
/**
-
修改文档数据
*/
@Test
public void updateDoc(){
Map<String, Object> stuMap = new HashMap<>();
stuMap.put(“name”, “秦王嬴政”);
stuMap.put(“age”, 2000);Document doc = Document.from(stuMap);
UpdateQuery updateQuery = UpdateQuery.builder(“10011”)
.withDocument(doc)
.build();
IndexCoordinates indexCoordinate = IndexCoordinates.of(“stu”);esTemplate.update(updateQuery, indexCoordinate);
}
/******************** 分词搜索 ********************/
/**
-
初始化数据
*/
@Test
public void init() {esTemplate.indexOps(Stu.class).delete();
esTemplate.indexOps(Stu.class).create();Stu stu0 = new Stu(10020L, “didiok”, 18, 100.5f, true);
Stu stu1 = new Stu(10021L, “放下”, 20, 88.5f, true);
- 创建索引
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数大数据工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年大数据全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上大数据开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新
如果你觉得这些内容对你有帮助,可以添加VX:vip204888 (备注大数据获取)
一个人可以走的很快,但一群人才能走的更远。不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎扫码加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
U-1712990104274)]
[外链图片转存中…(img-eHfVy7xr-1712990104275)]
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上大数据开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新
如果你觉得这些内容对你有帮助,可以添加VX:vip204888 (备注大数据获取)
[外链图片转存中…(img-XzXn1w53-1712990104275)]
一个人可以走的很快,但一群人才能走的更远。不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎扫码加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!