ElasticSearch Java API的使用和介绍
1. 介绍
Spring Data ElasticSearch:是Spring针对ElasticSearch操作提供的一套Java API,底层是对ES官方所提供的Java API进行了封装,用来简化ES的操作。
2. ES官方提供的Java API:RestHighLevelClient
注:当导入spring-boot-starter-data-elasticsearch依赖的时候,Spring Boot已经实现了RestHighLevelClient的自动化配置,在Spring容器中已经存在了该类的对象
2.1 基本方法
public final IndexResponse index(IndexRequest indexRequest, RequestOptions options) throws IOException
public final GetResponse get(GetRequest getRequest, RequestOptions options) throws IOException
public final UpdateResponse update(UpdateRequest updateRequest, RequestOptions options) throws IOException public final DeleteResponse delete(DeleteRequest deleteRequest, RequestOptions options) throws IOException
2.2 核心方法:
public final SearchResponse search(SearchRequest searchRequest, RequestOptions options) throws IOException
2.3 代码演示
@SpringBootTest(classes = SearchApplication.class)
public class RestHighLevelClientTest {
@Autowired
private RestHighLevelClient restHighLevelClient;
/**
* 保存文档数据
* @throws IOException
*/
@Test
public void saveDocument() throws IOException {
// 创建添加文档的请求对象
IndexRequest indexRequest = new IndexRequest("person").id("1");
// 准备数据
Person person = new Person();
person.setId(1L);
person.setUsername("1");
person.setAddress("2");
person.setAge(20);
String json = JSON.toJSONString(person);
// 把数据设置给indexRequest对象
indexRequest.source(json, XContentType.JSON);
// 发送请求
IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(indexResponse);
}
/**
* 查询文档数据
*/
@Test
public void getDocument() throws IOException {
GetRequest getRequest = new GetRequest("person").id("1");
GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
String sourceAsString = getResponse.getSourceAsString();
System.out.println(sourceAsString);
}
/**
* 修改文档数据
* @throws IOException
*/
@Test
public void updateDocument() throws IOException {
UpdateRequest updateRequest = new UpdateRequest("person", "1");
Person person = new Person();
person.setId(1L);
person.setUsername("1");
person.setAddress("2");
person.setAge(30);
String json = JSON.toJSONString(person);
updateRequest.doc(json, XContentType.JSON);
UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(updateResponse);
}
/**
* 高级搜索
*/
@Test
public void search() throws IOException {
SearchRequest searchRequest = new SearchRequest("person");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchRequest.source(searchSourceBuilder);
SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits searchHits = response.getHits();
long count = searchHits.getTotalHits().value;
System.out.println(count);
SearchHit[] searchHitsHits = searchHits.getHits();
for (SearchHit searchHit : searchHitsHits) {
String source = searchHit.getSourceAsString();
System.out.println(source);
}
}
}
3. ElasticSearchRestTemplate
使用Spring Data ES的时候,首先需要建立实体类和ES索引库之间的对应关系,然后就是建立实体类中的属性和索引库字段之间的映射关系。
@Data
@Document(indexName = "goods" , shards = 3 , replicas = 2)
public class Goods {
@Id
private Long id;
// String 在 es中可以对应 Text(要分词) 、 Keyword(无需分词存)
// index = false,无需索引。这个字段不会用来检索,不用建立索引
@Field(type = FieldType.Keyword, index = false)
private String defaultImg;
@Field(type = FieldType.Text, analyzer = "ik_smart")
private String title;
@Field(type = FieldType.Double)
private BigDecimal price;
// @Field(type = FieldType.Date)
@Field(type = FieldType.Date,format = DateFormat.custom,pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
@Field(type = FieldType.Long)
private Long tmId;
@Field(type = FieldType.Keyword)
private String tmName;
@Field(type = FieldType.Keyword)
private String tmLogoUrl;
@Field(type = FieldType.Long)
private Long category1Id;
@Field(type = FieldType.Keyword)
private String category1Name;
@Field(type = FieldType.Long)
private Long category2Id;
@Field(type = FieldType.Keyword)
private String category2Name;
@Field(type = FieldType.Long)
private Long category3Id;
@Field(type = FieldType.Keyword)
private String category3Name;
@Field(type = FieldType.Long)
private Long hotScore = 0L;
// Nested 支持嵌套查询
@Field(type = FieldType.Nested)
private List<SearchAttr> attrs;
}
3.1 基本方法
public <T> Iterable<T> save(T... entities)
public <T> T get(String id, Class<T> clazz)
UpdateResponse update(UpdateQuery updateQuery, IndexCoordinates index);
void delete(DeleteQuery query, IndexCoordinates index);
3.2 核心方法
public <T> SearchHits<T> search(Query query, Class<T> clazz)
Query对象的构建可以使用:NativeSearchQueryBuilder
3.3 代码实现
@SpringBootTest(classes = SearchApplication.class)
public class ElasticsearchRestTemplateTest {
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
/**
* 新增
*/
@Test
public void addDocument(){
Person person = new Person();
person.setId(1L);
person.setUsername("1");
person.setAddress("2");
person.setAge(30);
elasticsearchRestTemplate.save(person);
}
/**
* 查询
*/
@Test
public void getDocument(){
Person person = elasticsearchRestTemplate.get("1", Person.class, IndexCoordinates.of("person"));
System.out.println(person);
}
/**
* 修改
*/
@Test
public void updateDocument(){
Document document = Document.create();
document.put("username", "不摇碧莲");
UpdateQuery updateQuery = UpdateQuery.builder("1")
.withDocument(document)
.build();
elasticsearchRestTemplate.update(updateQuery, IndexCoordinates.of("person"));
}
/**
* 高级搜索
*/
@Test
public void search(){
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchAllQuery())
.withPageable(PageRequest.of(0, 2))
.build();
SearchHits<Person> searchHits = elasticsearchRestTemplate.search(searchQuery, Person.class, IndexCoordinates.of("person"));
List<SearchHit<Person>> searchHitList = searchHits.getSearchHits();
searchHitList.forEach(searchHit -> {
Person person = searchHit.getContent();
System.out.println(person);
});
}
}
4. ElasticSearchRepository
Spring Data ES提供了ElasticSearchRepository持久层操作的接口,在该接口中定义了基本的CRUD方法。
4.1 使用思想
- 定义一个接口继承ElasticSearchRepository接口
public interface GoodsRepository extends ElasticsearchRepository<Goods, Long> {
}
注:使用了ElasticsearchRepository接口以后,在项目启动的时候会自动进行索引库的创建,需要给字段指定type属性值
2. 从Spring容器中获取该接口的代理对象,然后进行CRUD操作
4.2 代码实现
@SpringBootTest(classes = SearchApplication.class)
public class ElasticsearchRepositoryTest {
@Autowired
private PersonRepository personRepository;
@Test
public void add(){
Person person = new Person();
person.setId(1L);
person.setUsername("1");
person.setAddress("2");
person.setAge(30);
personRepository.save(person);
}
@Test
public void findById(){
Optional<Person> optional = personRepository.findById(1L);
Person person = optional.get();
System.out.println(person);
}
@Test
public void update(){
Person person = new Person();
person.setId(2L);
person.setUsername("1");
person.setAddress("2");
person.setAge(20);
personRepository.save(person);
}
@Test
public void delete(){
personRepository.deleteById(1L);
}
}
作者:摆烂ing
出处:http://www.cnblogs.com/insilently/
版权:本文版权归作者所有
转载:欢迎转载,但未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必追究法律责任
出处:http://www.cnblogs.com/insilently/
版权:本文版权归作者所有
转载:欢迎转载,但未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必追究法律责任

浙公网安备 33010602011771号