ElasticSearch 基础知识二分析

访客 阅读:261 2021-03-31 14:12:00 评论:0

第一、ElasticSearch 基础操作之增删改查

1.1 pom.xml 添加相关ElasticSearch jar包依赖。

<!-- elasticseacher 依赖jar 包 --> 
		<dependency> 
			<groupId>org.elasticsearch</groupId> 
			<artifactId>elasticsearch</artifactId> 
			<version>6.3.2</version> 
		</dependency> 
		<dependency> 
			<groupId>org.elasticsearch.client</groupId> 
			<artifactId>transport</artifactId> 
			<version>6.3.2</version> 
		</dependency>

1.2 ElasticSearch 通用工具类封装:

package com.zzg.elasticsearch; 
 
import java.net.InetAddress; 
 
import org.elasticsearch.client.transport.TransportClient; 
import org.elasticsearch.common.settings.Settings; 
import org.elasticsearch.common.transport.TransportAddress; 
import org.elasticsearch.transport.client.PreBuiltTransportClient; 
 
 
/** 
 * elasticSearch 工具类 
 *  
 * @author Administrator 
 * 
 */ 
public class ElasticSearchUtil { 
 
	public Settings getSettings(String clusterName) { 
		return Settings.builder().put("cluster.name", clusterName).build(); 
	} 
 
	public TransportClient getTransportClient(Settings settings, String ip, Integer port) { 
		TransportClient client = null; 
		try { 
			client = new PreBuiltTransportClient(settings) 
					.addTransportAddress(new TransportAddress(InetAddress.getByName(ip), port)); 
		} catch (Exception e) { 
			e.printStackTrace(); 
		} 
		return client; 
	} 
 
	public void close(TransportClient client) { 
		client.close(); 
	} 
	 
   // 功能代码片段 
	public void createIndex(TransportClient client, String indexName) { 
		client.admin().indices().prepareCreate(indexName).get(); 
	} 
 
} 

1.3 创建Index

测试核心功能代码:

// TODO Auto-generated method stub 
		ElasticSearchUtil util = new ElasticSearchUtil(); 
		Settings settings = util.getSettings("my-application"); 
		TransportClient client = util.getTransportClient(settings, "localhost", 9300); 
		util.createIndex(client, "blog1"); 
		util.close(client);

elasticSearch head 管理平台截图:

 

 1.4 创建映射Mapping

注意:ElasticSearchUtil  补全创建Mapping 方法。

	public void createMapping(TransportClient client, String indexName, String type, XContentBuilder builder) { 
		// 创建映射  
		try { 
			PutMappingRequest mapping = Requests.putMappingRequest(indexName) .type(type).source(builder);  
			client.admin().indices().putMapping(mapping).get(); 
		}catch(Exception e) { 
			e.printStackTrace(); 
		} 
		 
	} 

核心功能代码:

/** 
	 * 创建mapping 映射 
	 *  
	 * @param args 
	 */ 
	public static void main(String[] args) { 
		ElasticSearchUtil util = new ElasticSearchUtil(); 
		Settings settings = util.getSettings("my-application"); 
		TransportClient client = util.getTransportClient(settings, "localhost", 9300); 
		XContentBuilder builder = getMapping(); 
		util.createMapping(client, "blog1", "article", builder); 
		util.close(client); 
	} 
 
	public static XContentBuilder getMapping() { 
		XContentBuilder builder = null; 
		try { 
			builder = XContentFactory.jsonBuilder().startObject().startObject("article").startObject("properties") 
					.startObject("id").field("type", "integer").field("store", true).endObject().startObject("title") 
					.field("type", "text").field("store", true).field("analyzer", "ik_smart").endObject() 
					.startObject("content").field("type", "text").field("store", true).field("analyzer", "ik_smart") 
					.endObject().endObject().endObject().endObject(); 
		} catch (IOException e) { 
			// TODO Auto-generated catch block 
			e.printStackTrace(); 
		} 
		return builder; 
	} 

elasticSearch head 管理平台截图:

  1.5 创建document

注意:ElasticSearchUtil  补全创建Document方法。

public void createDocument(TransportClient client, String indexName, String type, String id, XContentBuilder source) { 
		client.prepareIndex(indexName, type, id).setSource(source).get(); 
	}

核心功能代码:

/** 
	 * 创建document 文档对象 
	 * @param args 
	 */ 
	public static void main(String[] args) { 
		ElasticSearchUtil util = new ElasticSearchUtil(); 
		Settings settings = util.getSettings("my-application"); 
		TransportClient client = util.getTransportClient(settings, "localhost", 9300); 
		XContentBuilder source = getMapping(); 
		util.createDocument(client, "blog1", "article", "1", source); 
		util.close(client); 
	} 
	 
	public static XContentBuilder  getMapping() { 
		XContentBuilder builder = null; 
		try { 
			 builder = XContentFactory.jsonBuilder() .startObject() .field("id", 1) .field("title", "ElasticSearch是一个基于Lucene的搜索服务器") 
					.field("content", "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用 Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到 实时搜索,稳定,可靠,快速,安装使用方便。")  
					.endObject(); // 建立文档对象 
		}catch(Exception e) { 
			e.printStackTrace(); 
		} 
		return builder; 
		 
	}

elasticSearch head 管理平台截图:

   1.6 查询document

1.6.1 关键字查询

核心功能代码:

package com.zzg.elasticsearch; 
 
import java.util.Iterator; 
 
import org.elasticsearch.action.search.SearchResponse; 
import org.elasticsearch.client.transport.TransportClient; 
import org.elasticsearch.common.settings.Settings; 
import org.elasticsearch.index.query.QueryBuilders; 
import org.elasticsearch.search.SearchHit; 
import org.elasticsearch.search.SearchHits; 
 
public class ElasticSearchQuery { 
	 
	private ElasticSearchUtil util; 
	 
	public ElasticSearchUtil getUtil() { 
		return util; 
	} 
 
	public void setUtil(ElasticSearchUtil util) { 
		this.util = util; 
	} 
	 
	public ElasticSearchQuery(ElasticSearchUtil util) { 
		super(); 
		this.util = util; 
	} 
 
	/** 
	 * 关键字查询 
	 */ 
	public void termQuery(String indexName, String type, String field, String value) { 
		Settings settings = util.getSettings("my-application"); 
		TransportClient client = util.getTransportClient(settings, "localhost", 9300); 
		 
		//2、设置搜索条件  
		SearchResponse searchResponse = client.prepareSearch(indexName) .setTypes(type) .setQuery(QueryBuilders.termQuery(field, value)).get();  
		//3、遍历搜索结果数据  
		SearchHits hits = searchResponse.getHits(); 
		// 获取命中次数,查询结果有多少对象 
		System.out.println("查询结果有:" + hits.getTotalHits() + "条"); 
		Iterator<SearchHit> iterator = hits.iterator(); 
		while (iterator.hasNext()) {  
			SearchHit searchHit = iterator.next();  
			// 每个查询对象  
			System.out.println(searchHit.getSourceAsString()); 
			// 获取字符串格式打印  
			System.out.println("title:" + searchHit.getSourceAsMap().get("title"));  
		} 
	} 
		 
 
} 

测试核心功能代码:

	public static void main(String[] args) { 
		ElasticSearchUtil util = new ElasticSearchUtil(); 
		ElasticSearchQuery query = new ElasticSearchQuery(util); 
		query.termQuery("blog1", "article", "content", "搜索"); 
	}

 效果截图:

1.6.2 字符串查询

注意:ElasticSearchQuery  工具类补全字符串查询方法

/** 
	 * 字符串查询 
	 * @param indexName 
	 * @param type 
	 * @param field 
	 * @param value 
	 */ 
	public void stringQuery(String indexName, String type, String value) { 
		Settings settings = util.getSettings("my-application"); 
		TransportClient client = util.getTransportClient(settings, "localhost", 9300); 
		 
		//2、设置搜索条件  
		SearchResponse searchResponse = client.prepareSearch(indexName) .setTypes(type) .setQuery(QueryBuilders.queryStringQuery(value)).get();  
		//3、遍历搜索结果数据  
		SearchHits hits = searchResponse.getHits(); 
		// 获取命中次数,查询结果有多少对象 
		System.out.println("查询结果有:" + hits.getTotalHits() + "条"); 
		Iterator<SearchHit> iterator = hits.iterator(); 
		while (iterator.hasNext()) {  
			SearchHit searchHit = iterator.next();  
			// 每个查询对象  
			System.out.println(searchHit.getSourceAsString()); 
			// 获取字符串格式打印  
			System.out.println("title:" + searchHit.getSourceAsMap().get("title"));  
		} 
	}

测试核心功能代码:

 

	public static void main(String[] args) { 
		ElasticSearchUtil util = new ElasticSearchUtil(); 
		ElasticSearchQuery query = new ElasticSearchQuery(util); 
		query.stringQuery("blog1", "article", "搜索"); 
	}

效果截图:

1.6.3 文档ID查询

注意:ElasticSearchQuery  工具类补全ID查询方法

	/** 
	 * id 查询 
	 * @param indexName 
	 * @param type 
	 * @param value 
	 */ 
	public void idQuery(String indexName, String type, String id) { 
		Settings settings = util.getSettings("my-application"); 
		TransportClient client = util.getTransportClient(settings, "localhost", 9300); 
		 
		//2、设置搜索条件  
		SearchResponse searchResponse = client.prepareSearch(indexName) .setTypes(type) .setQuery(QueryBuilders.idsQuery().addIds(id)).get();  
		//3、遍历搜索结果数据  
		SearchHits hits = searchResponse.getHits(); 
		// 获取命中次数,查询结果有多少对象 
		System.out.println("查询结果有:" + hits.getTotalHits() + "条"); 
		Iterator<SearchHit> iterator = hits.iterator(); 
		while (iterator.hasNext()) {  
			SearchHit searchHit = iterator.next();  
			// 每个查询对象  
			System.out.println(searchHit.getSourceAsString()); 
			// 获取字符串格式打印  
			System.out.println("title:" + searchHit.getSourceAsMap().get("title"));  
		} 
	}

测试核心功能代码:

public static void main(String[] args) { 
		ElasticSearchUtil util = new ElasticSearchUtil(); 
		ElasticSearchQuery query = new ElasticSearchQuery(util); 
		query.idQuery("blog1", "article", "1"); 
	}

效果截图:

1.7 查询分页document 

1.7.1 批量新增文档

核心功能代码:

package com.zzg.elasticsearch; 
 
import org.elasticsearch.client.transport.TransportClient; 
import org.elasticsearch.common.settings.Settings; 
import org.elasticsearch.common.xcontent.XContentType; 
 
import com.alibaba.fastjson.JSONObject; 
 
public class ElasticSearchBatch { 
	private ElasticSearchUtil util; 
 
	public ElasticSearchUtil getUtil() { 
		return util; 
	} 
 
	public void setUtil(ElasticSearchUtil util) { 
		this.util = util; 
	} 
 
	public ElasticSearchBatch(ElasticSearchUtil util) { 
		super(); 
		this.util = util; 
	} 
 
	/** 
	 * elasticSearch 批量插入 
	 */ 
	public void batchInsert(String indexName, String type) { 
		Settings settings = util.getSettings("my-application"); 
		TransportClient client = util.getTransportClient(settings, "localhost", 9300); 
 
		 
		for (int i = 2; i <= 100; i++) { 
			// 描述json 数据 
			Article article = new Article(); 
			article.setId(i); 
			article.setTitle(i + "搜索工作其实很快乐"); 
			article.setContent(i 
					+ "我们希望我们的搜索解决方案要快,我们希望有一个零配置和一个完全免费的搜索模式,我 们希望能够简单地使用JSON通过HTTP的索引数据,我们希望我们的搜索服务器始终可用,我们希望能够一台开始并扩展 到数百,我们要实时搜索,我们要简单的多租户,我们希望建立一个云的解决方案。Elasticsearch旨在解决所有这些 问题和更多的问题。"); 
			// 建立文档 
			client.prepareIndex(indexName, type, article.getId().toString()) 
					.setSource(JSONObject.toJSONString(article), XContentType.JSON).get(); 
		} 
	} 
	 
	/** 
	 * 定义数据内部类 
	 * @author Administrator 
	 * 
	 */ 
	class Article{ 
		private Integer id; 
		private String title; 
		private String content; 
		public Integer getId() { 
			return id; 
		} 
		public void setId(Integer id) { 
			this.id = id; 
		} 
		public String getTitle() { 
			return title; 
		} 
		public void setTitle(String title) { 
			this.title = title; 
		} 
		public String getContent() { 
			return content; 
		} 
		public void setContent(String content) { 
			this.content = content; 
		} 
		 
		 
	} 
 
} 

测试核心功能代码:

	public static void main(String[] args) { 
		ElasticSearchUtil util = new ElasticSearchUtil(); 
		ElasticSearchBatch batch = new ElasticSearchBatch(util); 
		batch.batchInsert("blog1", "article"); 
	}

效果截图:

 1.7.2 关键字分页查询

注意:ElasticSearchQuery  工具类补全关键字分页查询功能

/** 
	 * 关键字分页查询 
	 */ 
	public void termQueryPage(String indexName, String type, String field, String value, int from, int size) { 
		Settings settings = util.getSettings("my-application"); 
		TransportClient client = util.getTransportClient(settings, "localhost", 9300); 
		 
		//2、设置搜索条件  
		SearchResponse searchResponse = client.prepareSearch(indexName) .setTypes(type) .setQuery(QueryBuilders.termQuery(field, value)) 
				.setFrom(from) 
				.setSize(size) 
				.get();  
		//3、遍历搜索结果数据  
		SearchHits hits = searchResponse.getHits(); 
		// 获取命中次数,查询结果有多少对象 
		System.out.println("查询结果有:" + hits.getTotalHits() + "条"); 
		Iterator<SearchHit> iterator = hits.iterator(); 
		while (iterator.hasNext()) {  
			SearchHit searchHit = iterator.next();  
			// 每个查询对象  
			System.out.println(searchHit.getSourceAsString()); 
			// 获取字符串格式打印  
			System.out.println("title:" + searchHit.getSourceAsMap().get("title"));  
		} 
	}

测试核心功能代码:

	public static void main(String[] args) { 
	 
		ElasticSearchUtil util = new ElasticSearchUtil(); 
		ElasticSearchQuery query = new ElasticSearchQuery(util); 
		query.termQueryPage("blog1", "article", "content", "搜索", 0, 10); 
	} 
	

效果截图:

字符串、ID查询实现分页,在查询条件上补全分页方法:    .setFrom(from) .setSize(size) 

1.8 高亮查询

1.8.1 什么是高亮显示

在进行关键字搜索时,搜索出的内容中的关键字会显示不同的颜色,称之为高亮。

1.8.2 高亮显示功能实现

注意:ElasticSearchQuery  工具类补全关键字分页高亮查询功能

	/** 
	 * 关键字查询之高亮显示 
	 * @param indexName 
	 * @param type 
	 * @param field 
	 * @param value 
	 * @param from 
	 * @param size 
	 */ 
	public void termQueryHighlight(String indexName, String type, String field, String value, int from, int size) { 
		Settings settings = util.getSettings("my-application"); 
		TransportClient client = util.getTransportClient(settings, "localhost", 9300); 
		//设置高亮数据 
				HighlightBuilder hiBuilder=new HighlightBuilder();  
				hiBuilder.preTags("<font style='color:red'>");  
				hiBuilder.postTags("</font>");  
				hiBuilder.field("title");  
		//2、设置搜索条件  
		SearchResponse searchResponse = client.prepareSearch(indexName) .setTypes(type) .setQuery(QueryBuilders.termQuery(field, value)) 
				.highlighter(hiBuilder) 
				.get();  
		 
		//3、遍历搜索结果数据  
		SearchHits hits = searchResponse.getHits(); 
		// 获取命中次数,查询结果有多少对象 
		System.out.println("查询结果有:" + hits.getTotalHits() + "条"); 
		Iterator<SearchHit> iterator = hits.iterator(); 
		while (iterator.hasNext()) {  
			SearchHit searchHit = iterator.next();  
			System.out.println("String方式打印文档搜索内容:");  
			System.out.println(searchHit.getSourceAsString()); 
			System.out.println("Map方式打印高亮内容"); 
			System.out.println(searchHit.getHighlightFields()); 
			System.out.println("遍历高亮集合,打印高亮片段:");  
			if(searchHit.getHighlightFields() != null) { 
				if(searchHit.getHighlightFields().get("title") != null) { 
					Text[] text = searchHit.getHighlightFields().get("title").getFragments();  
					for (Text str : text) {  
						System.out.println(str);  
					}	 
					 
				} 
			} 
			 
		} 
	}
测试核心功能代码:
	public static void main(String[] args) { 
		 
		ElasticSearchUtil util = new ElasticSearchUtil(); 
		ElasticSearchQuery query = new ElasticSearchQuery(util); 
		query.termQueryHighlight("blog1", "article", "content", "搜索", 0, 10); 
	}

第二、Spring Data ElasticSearch 基础操作之增删改查

2.1 SpringData ElasticSearch 简介

2.1.1 什么是SpringData

Spring Data 是一个用于简化数据库访问,并支持云服务的开源框架。其主要目标是使得对数据的访问变得方便快
捷,并支持 map-reduce 框架和云计算数据服务。 Spring Data 可以极大的简化 JPA 的写法,可以在几乎不用写实现
的情况下,实现对数据的访问和操作。除了 CRUD 外,还包括如分页、排序等一些常用的功能。
Spring Data 的官网: http://projects.spring.io/spring-data/
Spring Data 常用的功能模块如下:

 2.1.2 什么是SpringData ElasticSearch

Spring Data ElasticSearch 基于 spring data API 简化 elasticSearch操作,将原始操作elasticSearch的客户端API 进行封装 。Spring Data为Elasticsearch项目提供集成搜索引擎。Spring Data Elasticsearch POJO的关键功能区域 为中心的模型与Elastichsearch交互文档和轻松地编写一个存储库数据访问层。

官方网站:http://projects.spring.io/spring-data-elasticsearch/

 2.1.3 SpringBoot 集成SpringData ElasticSearch

项目结构截图:

elasticsearch-demo 之pom.xml 添加相关jar 包依赖:

<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>com.zzg</groupId> 
		<artifactId>elasticSearch-example</artifactId> 
		<version>0.0.1-SNAPSHOT</version> 
	</parent> 
	<artifactId>elasticsearch-demo</artifactId> 
	<properties> 
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 
		<java.version>1.8</java.version> 
 
		<elasticsearch.version>6.3.2</elasticsearch.version> 
		<spring.data.elasticsearch.version>3.1.0.RELEASE</spring.data.elasticsearch.version> 
	</properties> 
 
	<dependencies> 
		<dependency> 
			<groupId>org.elasticsearch</groupId> 
			<artifactId>elasticsearch</artifactId> 
			<version>${elasticsearch.version}</version> 
		</dependency> 
		<dependency> 
			<groupId>org.elasticsearch.client</groupId> 
			<artifactId>transport</artifactId> 
			<version>${elasticsearch.version}</version> 
		</dependency> 
		<dependency> 
			<groupId>org.elasticsearch.client</groupId> 
			<artifactId>elasticsearch-rest-client</artifactId> 
			<version>${elasticsearch.version}</version> 
		</dependency> 
		<dependency> 
			<groupId>org.elasticsearch.plugin</groupId> 
			<artifactId>transport-netty4-client</artifactId> 
			<version>${elasticsearch.version}</version> 
		</dependency> 
		<dependency> 
			<groupId>org.springframework.data</groupId> 
			<artifactId>spring-data-elasticsearch</artifactId> 
			<version>${spring.data.elasticsearch.version}</version> 
		</dependency> 
		<dependency> 
			<groupId>org.springframework.boot</groupId> 
			<artifactId>spring-boot-starter-data-elasticsearch</artifactId> 
		</dependency> 
	</dependencies> 
</project>

程序入口:

package com.zzg; 
 
import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 
import org.springframework.boot.builder.SpringApplicationBuilder; 
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; 
 
 
@SpringBootApplication 
public class Application extends SpringBootServletInitializer { 
 
	public static void main(String[] args) { 
		// TODO Auto-generated method stub 
		 SpringApplication.run(Application.class, args); 
	} 
	 
	@Override 
	protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { 
		// TODO Auto-generated method stub 
		return builder.sources(Application.class); 
	} 
	 
 
} 

实体对象:

package com.zzg.entity; 
 
import java.io.Serializable; 
 
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.FieldType; 
 
@Document(indexName = "blog3", type = "article") 
public class Article implements Serializable { 
 
	/** 
	 *  
	 */ 
	private static final long serialVersionUID = 5941564233618076170L; 
 
	// @Id 文档主键 唯一标识 
	@Id 
	// @Field 每个文档的字段配置(类型、是否分词、是否存储、分词器 ) 
	@Field(store = true, index = false, type = FieldType.Integer) 
	private Integer id; 
 
	@Field(index = true, analyzer = "ik_smart", store = true, searchAnalyzer = "ik_smart", type = FieldType.Text) 
	private String title; 
 
	@Field(index = true, analyzer = "ik_smart", store = true, searchAnalyzer = "ik_smart", type = FieldType.Text) 
	private String content; 
 
	public Integer getId() { 
		return id; 
	} 
 
	public void setId(Integer id) { 
		this.id = id; 
	} 
 
	public String getTitle() { 
		return title; 
	} 
 
	public void setTitle(String title) { 
		this.title = title; 
	} 
 
	public String getContent() { 
		return content; 
	} 
 
	public void setContent(String content) { 
		this.content = content; 
	} 
 
	@Override 
	public String toString() { 
		return "Article [id=" + id + ", title=" + title + ", content=" + content + "]"; 
	} 
 
} 

ElasticSearch Repository接口定义:

package com.zzg.repository; 
 
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; 
import org.springframework.stereotype.Repository; 
 
import com.zzg.entity.Article; 
 
@Repository 
public interface ArticleRepository extends ElasticsearchRepository<Article, Integer> { 
 
} 

实体对象服务定义及其实现类:

package com.zzg.service; 
 
import java.util.List; 
 
import org.springframework.data.domain.Page; 
 
import com.zzg.entity.Article; 
 
public interface ArticleService { 
	long count(); 
 
	Article save(Article article); 
 
    void delete(Article article); 
 
    Iterable<Article> getAll(); 
 
    List<Article> getByName(String name); 
 
    Page<Article> pageQuery(Integer pageNo, Integer pageSize, String kw); 
 
} 
package com.zzg.service.impl; 
 
import java.util.ArrayList; 
import java.util.List; 
 
import org.elasticsearch.index.query.MatchQueryBuilder; 
import org.elasticsearch.index.query.QueryBuilders; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.data.domain.Page; 
import org.springframework.data.domain.PageRequest; 
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; 
import org.springframework.data.elasticsearch.core.query.SearchQuery; 
import org.springframework.stereotype.Service; 
 
import com.zzg.entity.Article; 
import com.zzg.repository.ArticleRepository; 
import com.zzg.service.ArticleService; 
 
@Service 
public class ArticleServiceImpl implements ArticleService { 
	@Autowired 
	private ArticleRepository repository; 
 
	public long count() { 
		// TODO Auto-generated method stub 
		return repository.count(); 
	} 
 
	public Article save(Article article) { 
		// TODO Auto-generated method stub 
		return repository.save(article); 
	} 
 
	public void delete(Article article) { 
		// TODO Auto-generated method stub 
		repository.delete(article); 
	} 
 
	public Iterable<Article> getAll() { 
		// TODO Auto-generated method stub 
		return repository.findAll(); 
	} 
 
	public List<Article> getByName(String name) { 
		// TODO Auto-generated method stub 
		List<Article> list = new ArrayList<Article>();        
		MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("content", name); 
		Iterable<Article> iterable = repository.search(matchQueryBuilder); 
		  
		iterable.forEach(item ->{ 
			list.add(item); 
		}); 
		 
		return list;  
	} 
 
	public Page<Article> pageQuery(Integer pageNo, Integer pageSize, String kw) { 
		// TODO Auto-generated method stub 
		SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(QueryBuilders.matchPhraseQuery("content", kw)).withPageable(PageRequest.of(pageNo, pageSize)).build(); 
		return repository.search(searchQuery);   
	} 
 
} 

application.properties 配置文件定义:

spring.data.elasticsearch.cluster-name=my-application 
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300

ElasticSearch Test功能代码:

package com.zzg.test; 
 
import java.util.List; 
 
import org.junit.Test; 
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.domain.Pageable; 
import org.springframework.test.context.junit4.SpringRunner; 
 
import com.zzg.entity.Article; 
import com.zzg.service.ArticleService; 
 
@RunWith(SpringRunner.class) 
@SpringBootTest 
public class ElasticSearchTest { 
	@Autowired 
	private ArticleService commodityService; 
 
	@Test 
	public void contextLoads() { 
		System.out.println(commodityService.count()); 
	} 
 
	/** 测试保存文档 */ 
	@Test 
	public void saveArticle() { 
		Article article = new Article(); 
		article.setId(100); 
		article.setTitle("测试SpringData ElasticSearch"); 
		article.setContent( 
				"Spring Data ElasticSearch 基于 spring data API 简化 elasticSearch操 作,将原始操作elasticSearch的客户端API 进行封装 \n" 
						+ " Spring Data为Elasticsearch Elasticsearch项目提供集成搜索引擎"); 
		commodityService.save(article); 
	} 
 
	/** 测试保存 */ 
	@Test 
	public void save() { 
		Article article = new Article(); 
		article.setId(1001); 
		article.setTitle("elasticSearch 3.0版本发布"); 
		article.setContent("ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的 全文搜索引擎,基于RESTful web接口"); 
		commodityService.save(article); 
	} 
 
	/** 测试更新 */ 
	@Test 
	public void update() { 
		Article article = new Article(); 
		article.setId(1001); 
		article.setTitle("elasticSearch 3.0版本发布...更新"); 
		article.setContent("ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的 全文搜索引擎,基于RESTful web接口"); 
		commodityService.save(article); 
	} 
 
	/** 测试删除 */ 
	@Test 
	public void delete() { 
		Article article = new Article(); 
		article.setId(1001); 
		commodityService.delete(article); 
	} 
 
	/** 批量插入 */ 
	@Test 
	public void save100() { 
		for (int i = 1; i <= 99; i++) { 
			Article article = new Article(); 
			article.setId(i); 
			article.setTitle(i + "elasticSearch 3.0版本发布..,更新"); 
			article.setContent(i + "ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用 户能力的全文搜索引擎,基于RESTful web接口"); 
			commodityService.save(article); 
		} 
	} 
 
	/** 查询全部 */ 
	@Test 
	public void findAll() { 
		Iterable<Article> page = commodityService.getAll(); 
 
		page.forEach(item -> { 
			System.out.println("content is:" + item.getContent()); 
		}); 
	} 
 
	/** 
	 * 条件查询 
	 */ 
	@Test 
	public void findByName() { 
		List<Article> list = commodityService.getByName("搜索"); 
		list.forEach(item -> { 
			System.out.println("content is:" + item.getContent()); 
		}); 
	} 
 
	/** 
	 * 条件查询 
	 */ 
	@Test 
	public void findPage() { 
		Page<Article> page = commodityService.pageQuery(0, 10, "搜索"); 
		System.out.println(page.getTotalPages()); 
		System.out.println(page.getNumber()); 
		System.out.println(page.getContent()); 
	} 
 
} 

 

声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

发表评论
搜索
KIKK导航

KIKK导航

排行榜
关注我们

一个IT知识分享的公众号