SpringBoot整合ElasticSearch

目录

版本选择

引入依赖

yml配置

创建实体

实现ElasticsearchRepository

测试

使用ElasticsearchRestTemplate


版本选择

Elasticsearch 7.17.3 对应依赖 Spring Data Elasticsearch 4.4.x,对应springboot版本2.7.x

引入依赖

XML 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

yml配置

javascript 复制代码
spring:
  elasticsearch:
    uris: http://localhost:9200
    connection-timeout: 3s

创建实体

java 复制代码
@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;
}

实现ElasticsearchRepository

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

java 复制代码
@Repository
public interface EmployeeRepository extends ElasticsearchRepository<Employee, Long> {
    List<Employee> findByName(String name);
}

测试

java 复制代码
@Autowired
EmployeeRepository employeeRepository;

@Test
public void testDocument(){

   Employee employee = new Employee(1L,"666",1,18,"北京","java");
    //插入文档
   employeeRepository.save(employee);

   //根据id查询
    Optional<Employee> result = employeeRepository.findById(1L);
    log.info(String.valueOf(result.get()));

    //根据name查询
    List<Employee> list = employeeRepository.findByName("666");
    log.info(String.valueOf(list.get(0)));

}

使用ElasticsearchRestTemplate

ElasticsearchRestTemplate模板类,封装了便捷操作Elasticsearch的模板方法,包括索引 / 映射 / CRUD 等底层操作和高级操作。

java 复制代码
@Autowired
ElasticsearchRestTemplate elasticsearchRestTemplate;
java 复制代码
@Test
public void testCreateIndex(){
    //创建索引
    IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(IndexCoordinates.of("employee_index"));
    if (indexOperations.exists()) {
        log.info("索引已经存在");
    }else {
        //创建索引
        indexOperations.create();
    }
}
@Test
public void testDeleteIndex(){
    //删除索引
    IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(IndexCoordinates.of("employee_index"));
    indexOperations.delete();
}

文档操作

java 复制代码
@Test
public 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 = elasticsearchRestTemplate.search(builder.build(), Employee.class);
    List<SearchHit<Employee>> searchHits = search.getSearchHits();
    for (SearchHit hit: searchHits){
        log.info("返回结果:"+hit.toString());
    }

}

@Test
public void testInsertBatch(){
    List<Employee> employees = new ArrayList<>();
    employees.add(new Employee("2","张三",1,25,"北京","java"));
    employees.add(new Employee("3","李四",1,28,"山西","pytion"));
    employees.add(new Employee("4","小红",0,26,"天津","php"));

    List<IndexQuery> queries = new ArrayList<>();
    for (Employee employee : employees) {
        IndexQuery indexQuery = new IndexQuery();
        indexQuery.setId(employee.getId());
        String json = JSONObject.toJSONString(employee);
        indexQuery.setSource(json);
        queries.add(indexQuery);
    }
    //bulk批量插入
    elasticsearchRestTemplate.bulkIndex(queries,Employee.class);
}
相关推荐
Abladol-aj13 分钟前
并发和并行的基础知识
java·linux·windows
清水白石00813 分钟前
从一个“支付状态不一致“的bug,看大型分布式系统的“隐藏杀机“
java·数据库·bug
Elastic 中国社区官方博客3 小时前
使用 Elastic AI Assistant for Search 和 Azure OpenAI 实现从 0 到 60 的转变
大数据·人工智能·elasticsearch·microsoft·搜索引擎·ai·azure
吾日三省吾码6 小时前
JVM 性能调优
java
Estar.Lee6 小时前
查手机号归属地免费API接口教程
android·网络·后端·网络协议·tcp/ip·oneapi
弗拉唐7 小时前
springBoot,mp,ssm整合案例
java·spring boot·mybatis
oi777 小时前
使用itextpdf进行pdf模版填充中文文本时部分字不显示问题
java·服务器
2401_857610037 小时前
SpringBoot社团管理:安全与维护
spring boot·后端·安全
少说多做3437 小时前
Android 不同情况下使用 runOnUiThread
android·java