pom依赖:
<?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>
<groupId>com.leyou.demo</groupId>
<artifactId>elasticsearch</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>elasticsearch</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<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-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml文件配置:
spring:
data:
elasticsearch:
cluster-name: elasticsearch
cluster-nodes: 192.168.56.101:9300
映射
Spring Data通过注解来声明字段的映射属性,有下面的三个注解:
@Document
作用在类,标记实体类为文档对象,一般有两个属性- indexName:对应索引库名称
- type:对应在索引库中的类型
- shards:分片数量,默认5
- replicas:副本数量,默认1
@Id
作用在成员变量,标记一个字段作为id主键@Field
作用在成员变量,标记为文档的字段,并指定字段映射属性:- type:字段类型,取值是枚举:FieldType
- index:是否索引,布尔类型,默认是true
- store:是否存储,布尔类型,默认是false
- analyzer:分词器名称
实体类:
package com.leyou.es.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* @date 2019/1/11-9:16
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(indexName = "heima4",type = "item",shards = 1)
public class Item {
@Field(type = FieldType.Double,index = false)
Long id;
@Field(type = FieldType.Text,analyzer = "ik_smart")
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; // 图片地址
}
自定义接口做查询用:
package com.leyou.es;
import com.leyou.es.pojo.Item;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import java.util.List;
/**
* @date 2019/1/11-9:47
*/
public interface Repository extends ElasticsearchRepository<Item,Long> {
List<Item> findByPriceBetween(Double b,Double e);
}
测试类:
package com.leyou.esTest;
import com.leyou.es.pojo.Item;
import com.leyou.es.Repository;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
/**
* @date 2019/1/11-9:25
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class Test {
//复杂查询用
@Autowired
ElasticsearchTemplate template;
//做增删改查用
@Autowired
Repository repository;
@org.junit.Test
public void TestCreat(){
//创建索引库
template.createIndex(Item.class);
//创建映射
template.putMapping(Item.class);
}
@org.junit.Test
public void TestIndex(){
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/13123.jpg"));
list.add(new Item(3L, "华为META10", "手机", "华为", 4499.00, "http://image.leyou.com/13123.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"));
// 接收对象集合,实现批量新增
repository.saveAll(list);
}
@org.junit.Test
public void getIndex() {
//查询所有
Iterable<Item> all = repository.findAll();
for (Item item : all) {
System.out.println(item);
}
}
@org.junit.Test
public void getIndex2() {
//自定义条件查询
Iterable<Item> all = repository.findByPriceBetween(3000d, 4000d);
for (Item item : all) {
System.out.println(item);
}
}
@org.junit.Test
public void getIndex3() {
//创建原生查询器
NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
//创建查询条件
builder.withQuery(QueryBuilders.matchQuery("title", "小米手机"));
//创建过滤条件
builder.withSourceFilter(new FetchSourceFilter(new String[]{"title","price"},null));
//创建排序条件
builder.withSort(SortBuilders.fieldSort("price").order(SortOrder.DESC));
//分页(从0开始)
builder.withPageable(PageRequest.of(0,2 ));
//建立查询
SearchQuery query = builder.build();
Page<Item> items = repository.search(query);
System.out.println("总条数:"+items.getTotalElements());
System.out.println("总页数:"+items.getTotalPages());
List<Item> content = items.getContent();
for (Item item : content) {
System.out.println("内容:"+item);
}
}
@org.junit.Test
public void getIndex4() {
//创建原生查询器
NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
//聚和条件
builder.addAggregation(AggregationBuilders.terms("popolarBrand").field("brand"));
//查询返回带聚合的结果
AggregatedPage<Item> items = template.queryForPage(builder.build(), Item.class);
//解析聚合
Aggregations aggs = items.getAggregations();
//获取指定名称的聚合
StringTerms terms =aggs.get("popolarBrand");
//获取桶
List<StringTerms.Bucket> buckets = terms.getBuckets();
//获取数据
for (StringTerms.Bucket bucket : buckets) {
System.out.println("key:"+bucket.getKey());
System.out.println("docCount:"+bucket.getDocCount());
}
}
}