1.SpringBoot环境和测试类,我就不讲了。
2.yml中的配置
clustername:是es的集群名称,默认是elasticsearch
cluster-nodes:tcp的地址,不要写错。
spring:
data:
elasticsearch:
cluster-name: elasticsearch
cluster-nodes: 192.168.199.128:9300
3.注意:org.springframework.boot,的版本如果过高或者过低,都会和我的代码不一样,我的是2.0.6
4.实体类的创建,用于创建es索引库和mapping映射段
/*indexName:索引库名,shards分片,replicas:副本,type表名
* - `@Field` 作用在成员变量,标记为文档的字段,并指定字段映射属性:
- type:字段类型,取值是枚举:FieldType
- index:是否索引,布尔类型,默认是true
- store:是否存储,布尔类型,默认是false
- analyzer:分词器名称:ik_max_word*/
@Document(indexName = "item", shards = 1,replicas =0 , type="docs")
public class Item {
@Id
Long id;
@Field(type =FieldType.Text,analyzer = "ik_max_word")
String title; //标题
@Field(type = FieldType.Keyword)
String category;// 分类
@Field(type =FieldType.Keyword )
String brand; // 品牌
@Field(type =FieldType.Double )
Double price; // 价格
@Field(type =FieldType.Keyword ,index = false)
String images; // 图片地址
@Override
public String toString() {
return "Item{" +
"id=" + id +
", title='" + title + '\'' +
", category='" + category + '\'' +
", brand='" + brand + '\'' +
", price=" + price +
", images='" + images + '\'' +
'}';
}
public Item() {
}
public Item(Long id, String title, String category, String brand, Double price, String images) {
this.id = id;
this.title = title;
this.category = category;
this.brand = brand;
this.price = price;
this.images = images;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getImages() {
return images;
}
public void setImages(String images) {
this.images = images;
}
}
5.写一个结构,继承ElasticSearchRepository<实体类,主键类型>
6.测试代码
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringDataEsApplication.class)
public class elasticSearch {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Autowired
private ItemRepository itemRepository;
@Test
public void textIndex(){
elasticsearchTemplate.createIndex(Item.class);
elasticsearchTemplate.putMapping(Item.class);
}
@Test
public void testSave(){
Item item=new Item(1L, "小米手机7", " 手机",
"小米", 3499.00, "http://image.leyou.com/13123.jpg");
itemRepository.save(item);
}
@Test
public void testSaveAll(){
List<Item> list=new ArrayList<>();
list.add(new Item(1L, "小米手机7", "手机", "小米", 3299.00, "http://image.leyou.com/13123.jpg"));
list.add(new Item(2L, "坚果手机R1", "手机", "锤子", 3699.00, "http://image.leyou.com/123.jpg"));
list.add(new Item(3L, "华为META10", "手机", "华为", 4499.00, "http://image.leyou.com/3.jpg"));
list.add(new Item(4L, "小米Mix2S", "手机", "小米", 4299.00, "http://image.leyou.com/13123.jpg"));
list.add(new Item(5L, "荣耀V10", "手机", "华为", 2799.00, "http://image.leyou.com/13123.jpg"));
itemRepository.saveAll(list);
}
@Test
public void testFindById(){
Optional<Item> item = itemRepository.findById(1l);
System.out.println(item.get());
}
@Test
public void testSortFind(){
Iterable<Item> price = itemRepository.findAll(Sort.by("price").descending());
price.forEach((item)-> System.out.println(item));
// 或者price.forEach(System.out::println);
}
@Test
public void testFindByTitle(){
List<Item> shoujis = itemRepository.findByTitle("手机");
shoujis.forEach((shouji)-> System.out.println(shouji));
}
@Test
public void testFindPriceBetween(){
List<Item> byPriceBetween = itemRepository.findByPriceBetween(3600d, 5000d);
byPriceBetween.forEach(System.out::println);
}
@Test
public void testFindByCategory(){
List<Item> shoujis = itemRepository.findByCategory("手机");
shoujis.forEach((shouji)-> System.out.println(shouji));
}
@Test
public void testFindAll(){
Iterable<Item> all = itemRepository.findAll();
all.forEach(System.out::println);
}
/*高级查询*/
@Test
public void testQueryBuilders(){
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("title", "手机");
Iterable<Item> search = itemRepository.search(matchQueryBuilder);
search.forEach(System.out::println);
}
/*自定义构建器查询*/
@Test
public void testNativeSearchQueryBuilder(){
NativeSearchQueryBuilder searchQueryBuilder=new NativeSearchQueryBuilder();
//添加基本查询条件
searchQueryBuilder.withQuery(QueryBuilders.matchQuery("title", "手机"));
//执行查询,获取分页结果集
Page<Item> items = itemRepository.search(searchQueryBuilder.build());//默认添加分页
System.out.println(items.getTotalElements());
System.out.println(items.getTotalPages());
items.forEach(System.out::println);
}
/*分页查询*/
@Test
public void testPage(){
NativeSearchQueryBuilder QueryBuilder=new NativeSearchQueryBuilder();
//添加基本查询条件
QueryBuilder.withQuery(QueryBuilders.matchQuery("category","手机"));
//添加分页条件,页码从0开始,查询第二页每页两条
QueryBuilder.withPageable(PageRequest.of(1,2));
//执行查询,获取分页结果集
Page<Item> search = this.itemRepository.search(QueryBuilder.build());
System.out.println(search.getTotalPages());
System.out.println(search.getTotalElements());
search.getContent().forEach(System.out::println);
}
/*排序查询*/
@Test
public void testSort(){
NativeSearchQueryBuilder QueryBuilder=new NativeSearchQueryBuilder();
//添加基本查询条件
QueryBuilder.withQuery(QueryBuilders.matchQuery("category","手机"));
//添加排序
QueryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.ASC));
//执行查询,获取分页结果集
Page<Item> search = this.itemRepository.search(QueryBuilder.build());
System.out.println(search.getTotalPages());
System.out.println(search.getTotalElements());
search.getContent().forEach(System.out::println);
}
/*聚合查询*/
@Test
public void testAgg(){
NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder();
//定义聚合名称和聚合字段
searchQueryBuilder.addAggregation(AggregationBuilders.terms("brandAgg").field("brand"));
//过滤掉普通结果集,不包含任何字段,也不排除任何字段,等于不显示普通字段。
searchQueryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{},null));
//执行查询,要使用page中的AggregationPage字类,才能拿到aggregation聚合
AggregatedPage<Item> search = (AggregatedPage<Item>)itemRepository.search(searchQueryBuilder.build());
//想要在聚合中拿到桶,就需要使用其下的Terms-StringTerms字类,根据我们的聚合方式,使用的子类也不同
StringTerms brandAgg = (StringTerms)search.getAggregation("brandAgg");
List<StringTerms.Bucket> buckets = brandAgg.getBuckets();
buckets.forEach((bucket)->{
//打印聚合名称和词条数
System.out.println(bucket.getKeyAsString());
System.out.println(bucket.getDocCount());
});
}
//桶内嵌套度量
@Test
public void testAggAndDuliang(){
NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder();
//定义聚合名称和聚合字段
searchQueryBuilder.addAggregation(AggregationBuilders.terms("brandAgg").field("brand")
.subAggregation(AggregationBuilders.avg("price_avg").field("price")));
//过滤掉普通结果集,不包含任何字段,也不排除任何字段,等于不显示普通字段。
searchQueryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{},null));
//执行查询,要使用page中的AggregationPage字类,才能拿到aggregation聚合
AggregatedPage<Item> search = (AggregatedPage<Item>)itemRepository.search(searchQueryBuilder.build());
//想要在聚合中拿到桶,就需要使用其下的Terms-StringTerms字类,根据我们的聚合方式,使用的子类也不同
StringTerms brandAgg = (StringTerms)search.getAggregation("brandAgg");
List<StringTerms.Bucket> buckets = brandAgg.getBuckets();
buckets.forEach((bucket)->{
//打印聚合名称和词条数
System.out.println(bucket.getKeyAsString());
System.out.println(bucket.getDocCount());
//子聚合放入map中根据,map的key-子聚合名称获取聚合
Map<String, Aggregation> stringAggregationMap = bucket.getAggregations().asMap();
//依旧需要强转,avg需要转成InternalAvg
InternalAvg price_avg = (InternalAvg)stringAggregationMap.get("price_avg");
System.out.println(price_avg.getValue());
});
}
}
7.最后附上依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.itcast.elasticSearch</groupId>
<artifactId>SpringDate-ElasticSearch</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>