SpringBoot整合ElasticSearch
目录
版本选择
引入依赖
yml配置
创建实体
实现ElasticsearchRepository
测试
使用ElasticsearchRestTemplate
版本选择

Elasticsearch 7.17.3 对应依赖 Spring Data Elasticsearch 4.4.x,对应springboot版本2.7.x
引入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
yml配置
spring:elasticsearch:uris: http://localhost:9200connection-timeout: 3s
创建实体
@Data
@AllArgsConstructor
@Document(indexName = "employees")
public class Employee {@Idprivate 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的高级接口
@Repository
public interface EmployeeRepository extends ElasticsearchRepository<Employee, Long> {List<Employee> findByName(String name);
}
测试
@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 等底层操作和高级操作。
@Autowired
ElasticsearchRestTemplate elasticsearchRestTemplate;
@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();
}
文档操作
@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);
}