1. 程式人生 > >spring boot整合elasticsearch

spring boot整合elasticsearch

1.依賴

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

2.定義實體類AccessLog

package com.immo.supervise.vo;


import java.util.Date;

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldIndex;
import org.springframework.data.elasticsearch.annotations.FieldType;

import lombok.Data;
import lombok.experimental.Accessors;
/**
 * @Document 行
 * indexName = "supervise"  指定索引(資料庫)為supervise
 * type = "AccessLog"      	指定型別(表)為 AccessLog
 * shards=5  節點數(分割槽數)
 * replicas=1 每個分割槽預設的備份數
 * indexStoreType 索引檔案儲存型別
 * refreshInterval	重新整理間隔
 * @author Linhai.Tan 2018-4-27
 *
 */
@Data
@Accessors(chain = true)
@Document(indexName = "supervise", type = "AccessLog",shards=5,replicas=1,indexStoreType="fs",refreshInterval="-1")
public class AccessLog{
	
	@Id
	private String id;
	
	/**
	 * 請求使用者id
	 */
	private String userId;
	
	/**
	 * 請求使用者型別
	 */
	@Field(type=FieldType.Integer,index=FieldIndex.no)
	private Integer userType;
	
	/**
	 * 建立的時間
	 */
	@Field(index=FieldIndex.no,type=FieldType.Date)
	private Date createDate;
	
	/**
	 * 請求的url
	 */
	private String url;
	
	/**
	 * 請求的引數
	 */
	private String param;
	
	/**
	 * 返回的資料
	 */
	private String result;
}

3.繼承ElasticsearchService類

package com.immo.supervise.service;

import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import com.immo.supervise.vo.AccessLog;
/**
 * 繼承ElasticsearchRepositor<實體類,主鍵型別>類
 * @author Linhai.Tan 2018-4-27
 *
 */
public interface ElasticsearchService extends ElasticsearchRepository<AccessLog, String>{
	
}

4.程式碼中注入使用

package com.immo.supervise.interceptor;

import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.internal.matchers.Find;
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.domain.Pageable;
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.SpringJUnit4ClassRunner;

import com.alibaba.fastjson.JSONObject;
import com.immo.Application;
import com.immo.supervise.service.ElasticsearchService;
import com.immo.supervise.vo.AccessLog;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class ElasticsearchTest {

	int PAGE_SIZE = 15; // 預設分頁大小

	int PAGE_NUMBER = 0; // 預設當前分頁

	String SCORE_MODE_SUM = "sum"; // 權重分求和模式

	Float MIN_SCORE = 10.0F; // 由於無相關性的分值預設為1, 設定權重分最小值為10

	@Autowired(required = false)
	private ElasticsearchService elasticsearchService;

	@Test
	public void testFunction() {
		AccessLog log = new AccessLog();
		log.setUrl("http://xxxxxxxxx");

		// 儲存
		AccessLog save = elasticsearchService.save(log);
		System.out.println("儲存後返回的資料為:" + JSONObject.toJSON(save));
		System.out.println("儲存後查詢資料為:" + JSONObject.toJSON(elasticsearchService.findOne(save.getId())));


		// 修改資料
		AccessLog update = new AccessLog();
		update.setId(save.getId());
		update.setUrl("updateUrl");
		AccessLog updateResult = elasticsearchService.save(update);
		System.out.println("更新後的資料為:" + JSONObject.toJSON(updateResult));
		System.out.println("更新後查出來的資料為:" + JSONObject.toJSON(elasticsearchService.findOne(update.getId())));

		// 刪除
		elasticsearchService.delete(updateResult.getId());
		System.out.println("刪除後查出來的資料為:" + JSONObject.toJSON(elasticsearchService.findOne(update.getId())));

	}
	
	
	
	
	
	
	/**
     * 使用QueryBuilder
     * termQuery("key", obj) 完全匹配
     * termsQuery("key", obj1, obj2..)   一次匹配多個值
     * matchQuery("key", Obj) 單個匹配, field不支援萬用字元, 字首具高階特性
     * multiMatchQuery("text", "field1", "field2"..);  匹配多個欄位, field有萬用字元忒行
     * matchAllQuery();         匹配所有檔案
     */
	private SearchQuery getSearchQuery(String id) {
		// 分頁引數
		Pageable pageable = new PageRequest(PAGE_NUMBER, PAGE_SIZE);

		// 分數,並自動按分排序
		FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery()
				.add(QueryBuilders.boolQuery().should(QueryBuilders.termQuery("id", id)),
						ScoreFunctionBuilders.weightFactorFunction(1000)); // 權重:name 1000分
				/*.add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("message", q)),
						ScoreFunctionBuilders.weightFactorFunction(100));*/ // 權重:message 100分

		// 分數、分頁
		return new NativeSearchQueryBuilder().withPageable(pageable).withQuery(functionScoreQueryBuilder).build();
	}
}
注意:    pring boot 每個版本有對應的es版本,不然報錯