ElasticSearch整合开发之 ElasticSearchOptions 客户端操作
客户端对象
-
ElasticsearchOperations RestHighLevelClient 推荐
ElasticsearchOperations
-
特点: 始终使用面向对象方式操作 ES 索引: 用来存放相似文档集合 映射: 用来决定放入文档的每个字段以什么样方式录入到 ES 中 字段类型 分词器.. 文档: 可以被索引最小单元 json 数据格式
@Document(indexName = "products", createIndex = true)
public class Product {
@Id
private Integer id;
@Field(type = FieldType.Keyword)
private String title;
@Field(type = FieldType.Float)
private Double price;
@Field(type = FieldType.Text)
private String description;
//get set ...
}
//1. @Document(indexName = "products", createIndex = true) 用在类上 作用:代表一个对象为一个文档
-- indexName属性: 创建索引的名称
-- createIndex属性: 是否创建索引
//2. @Id 用在属性上 作用:将对象id字段与ES中文档的_id对应
//3. @Field(type = FieldType.Keyword) 用在属性上 作用:用来描述属性在ES中存储类型以及分词情况
-- type: 用来指定字段类型
索引文档
@Test
public void testCreate() throws IOException {
Product product = new Product();
product.setId(1); //存在id指定id 不存在id自动生成id
product.setTitle("怡宝矿泉水");
product.setPrice(129.11);
product.setDescription("我们喜欢喝矿泉水....");
elasticsearchOperations.save(product);
}
删除文档
@Test
public void testDelete() {
Product product = new Product();
product.setId(1);
String delete = elasticsearchOperations.delete(product);
System.out.println(delete);
}
查询文档
@Test
public void testGet() {
Product product = elasticsearchOperations.get("1", Product.class);
System.out.println(product);
}
更新文档
@Test
public void testUpdate() {
Product product = new Product();
product.setId(1);
product.setTitle("怡宝矿泉水");
product.setPrice(129.11);
product.setDescription("我们喜欢喝矿泉水,你们喜欢吗....");
elasticsearchOperations.save(product);//不存在添加,存在更新
}
删除所有
@Test
public void testDeleteAll() {
elasticsearchOperations.delete(Query.findAll(), Product.class);
}
查询所有
@Test
public void testFindAll() {
SearchHits<Product> productSearchHits = elasticsearchOperations.search(Query.findAll(), Product.class);
productSearchHits.forEach(productSearchHit -> {
System.out.println("id: " + productSearchHit.getId());
System.out.println("score: " + productSearchHit.getScore());
Product product = productSearchHit.getContent();
System.out.println("product: " + product);
});
}
