Spring Data Elasticsearch基本使用

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());
		}

	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章