Spring Boot整合ElasticSearch实战 - 第511篇

发布于:2024-05-16 ⋅ 阅读:(120) ⋅ 点赞:(0)

历史文章(文章累计500+)

国内最全的Spring Boot系列之一

国内最全的Spring Boot系列之二

国内最全的Spring Boot系列之三

国内最全的Spring Boot系列之四

国内最全的Spring Boot系列之五》

国内最全的Spring Boot系列之六

国内最全的Spring Boot系列之七》

日赚800,利用淘宝/闲鱼进行AI音乐售卖实操 - 第506篇

如何让AI生成自己喜欢的歌曲-AI音乐创作的正确方式 - 第507篇

ES全文检索[ES系列] - 第508篇

ES 深度分页问题及针对不同需求下的解决方案[ES系列] - 第509篇

抖音主播/电商人员有福了,利用Suno创作产品宣传,让产品动起来-小米Su7 - 第510篇

最近体验了下AI生成音乐,感觉效果很不错,有兴趣的可以访问如下地址体验一下:

https://suno3.cn/#/?i=8NCBS8_WXTT

Hi,大家好,我是悟纤。我就是我,不一样的烟火。我就是我,与众不同的小苹果。

这一节来看下在SpringBoot中如何集成ElasticSearch。

一、Spring Boot整合ElasticSearch

这里有一个版本的对应情况,最好对应上会比较好,不然会出现莫名其妙的问题。

https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#new-features.5-1-0

​1.1 创建项目

根据相应的版本,选择相应的Spring Boot版本,这里选择的是3.1.4版本。

1.2 添加依赖

在pom.xml文件添加依赖:

<dependencies>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-web</artifactId>    </dependency>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>    </dependency>    <dependency>        <groupId>org.projectlombok</groupId>        <artifactId>lombok</artifactId>    </dependency>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-test</artifactId>        <scope>test</scope>    </dependency></dependencies>

1.3 添加配置

在配置文件application.properties中添加配置:

spring.elasticsearch.uris = http://localhost:9200spring.elasticsearch.connection-timeout = 3s

1.4 创建实体

创建实体,使用@Field注解,添加字段在ES中的类型以及使用的分词器:

@Data@AllArgsConstructor@Document(indexName = "employees")public class Employee {    @Id    private Long id;    @Field(type= FieldType.Keyword)    private String name;    private int sex;    private int age;    @Field(type= FieldType.Text,analyzer="ik_max_word")    private String address;    private String remark;}

1.5实现ElasticsearchRepository

该接口是框架封装的用于操作Elastsearch的高级接口:

@Repositorypublic interface EmployeeRepository extends ElasticsearchRepository<Employee, Long> {    List<Employee> findByName(String name);}

1.6测试

@AutowiredEmployeeRepository employeeRepository;@Testvoid test() {    Employee employee = new Employee(1L,"悟纤",1,32,"福建福州","love coding");    //插入文档    employeeRepository.save(employee);    //根据id查询    Optional<Employee> result = employeeRepository.findById(1L);    System.out.println(String.valueOf(result.get()));    //根据name查询    List<Employee> list = employeeRepository.findByName("悟纤");    System.out.println(list.get(0));}

1.7使用ElasticsearchTemplate

@Resourceprivate ElasticsearchTemplate elasticsearchTemplate;@Testpublic void testCreateIndex(){    //创建索引    IndexOperations indexOperations = elasticsearchTemplate.indexOps(IndexCoordinates.of("employee_index"));    if (indexOperations.exists()) {        System.out.println("索引已经存在");    }else {        //创建索引        indexOperations.create();    }}@Testpublic void testDeleteIndex(){    //删除索引    IndexOperations indexOperations = elasticsearchTemplate.indexOps(IndexCoordinates.of("employee_index"));    indexOperations.delete();}@Testpublic void testQueryDocument(){    NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();    //查询    //builder.withQuery(QueryBuilders.matchQuery("address","公园"));    // 设置分页信息    builder.withPageable(PageRequest.of(0, 5));    // 设置排序    //builder.withSort(SortBuilders.fieldSort("age").order(SortOrder.DESC));    SearchHits<Employee> search = elasticsearchTemplate.search(builder.build(), Employee.class);    List<SearchHit<Employee>> searchHits = search.getSearchHits();    for (SearchHit hit: searchHits){        System.out.println("返回结果:"+hit.toString());    }}@Testpublic void testInsertBatch() throws JsonProcessingException {    List<Employee> employees = new ArrayList<>();    employees.add(new Employee(2l,"张三",1,25,"广州天河公园","java developer"));    employees.add(new Employee(3l,"李四",1,28,"广州荔湾大厦","java assistant"));    employees.add(new Employee(4l,"小红",0,26,"广州白云山公园","php developer"));    List<IndexQuery> queries = new ArrayList<>();    for (Employee employee : employees) {        IndexQuery indexQuery = new IndexQuery();        indexQuery.setId(employee.getId().toString());        ObjectMapper mapper = new ObjectMapper();        String json = mapper.writeValueAsString(employee);        indexQuery.setSource(json);        queries.add(indexQuery);    }    //bulk批量插入    elasticsearchTemplate.bulkIndex(queries,Employee.class);}

基本的集成用起来害死很简单的,关键在如何在实际的项目中进行合理的使用,这个是需要在具体的实战中进行自我摸索和探究的。


网站公告

今日签到

点亮在社区的每一天
去签到