目录
版本选择
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);
}