ElasticSearch第二天
ElasticSearch第二天
学习目标:
- 能够使用java客户端完成创建、删除索引的操作
- 能够使用java客户端完成文档的增删改的操作
- 能够使用java客户端完成文档的查询操作
- 能够完成文档的分页操作
- 能够完成文档的高亮查询操作
- 能够搭建Spring Data ElasticSearch的环境
- 能够完成Spring Data ElasticSearch的基本增删改查操作
- 能够掌握基本条件查询的方法命名规则
第一章 ElasticSearch编程操作
1.1 创建工程,导入坐标
pom.xml坐标
<dependencies><dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>5.6.8</version></dependency><dependency><groupId>org.elasticsearch.client</groupId><artifactId>transport</artifactId><version>5.6.8</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-to-slf4j</artifactId><version>2.9.1</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.24</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-simple</artifactId><version>1.7.21</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.12</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency>
</dependencies>
1.2 创建索引index
@Test
//创建索引
public void test1() throws Exception{// 创建Client连接对象Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));//创建名称为blog2的索引client.admin().indices().prepareCreate("blog2").get();//释放资源client.close();
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-r8aT491t-1638370275531)(image/1.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xj7xxgmk-1638370275533)(image/2.png)]
1.3 创建映射mapping
@Test
//创建映射
public void test3() throws Exception{// 创建Client连接对象Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));// 添加映射/*** 格式:* "mappings" : {"article" : {"dynamic" : "false","properties" : {"id" : { "type" : "string" },"content" : { "type" : "string" },"author" : { "type" : "string" }}}}*/XContentBuilder builder = XContentFactory.jsonBuilder().startObject().startObject("article").startObject("properties").startObject("id").field("type", "integer").field("store", "yes").endObject().startObject("title").field("type", "string").field("store", "yes").field("analyzer", "ik_smart").endObject().startObject("content").field("type", "string").field("store", "yes").field("analyzer", "ik_smart").endObject().endObject().endObject().endObject();// 创建映射PutMappingRequest mapping = Requests.putMappingRequest("blog2").type("article").source(builder);client.admin().indices().putMapping(mapping).get();//释放资源client.close();
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7kGdCYXc-1638370275535)(image/4.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-r5wi0cYE-1638370275536)(image/5.png)]
1.4 建立文档document
1.4.1 建立文档(通过XContentBuilder)
@Test
//创建文档(通过XContentBuilder)
public void test4() throws Exception{// 创建Client连接对象Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));//创建文档信息XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("id", 1).field("title", "ElasticSearch是一个基于Lucene的搜索服务器").field("content","它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。").endObject();// 建立文档对象/*** 参数一blog1:表示索引对象* 参数二article:类型* 参数三1:建立id*/client.prepareIndex("blog2", "article", "1").setSource(builder).get();//释放资源client.close();
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rMm3suAD-1638370275538)(image/6.png)]
1.4.2 建立文档(使用Jackson转换实体)
1)创建Article实体
public class Article {private Integer id;private String title;private String content;getter/setter...
}
2)添加jackson坐标
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.8.1</version>
</dependency>
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.8.1</version>
</dependency>
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.8.1</version>
</dependency>
3)代码实现
@Test
//创建文档(通过实体转json)
public void test5() throws Exception{// 创建Client连接对象Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));// 描述json 数据//{id:xxx, title:xxx, content:xxx}Article article = new Article();article.setId(2);article.setTitle("搜索工作其实很快乐");article.setContent("我们希望我们的搜索解决方案要快,我们希望有一个零配置和一个完全免费的搜索模式,我们希望能够简单地使用JSON通过HTTP的索引数据,我们希望我们的搜索服务器始终可用,我们希望能够一台开始并扩展到数百,我们要实时搜索,我们要简单的多租户,我们希望建立一个云的解决方案。Elasticsearch旨在解决所有这些问题和更多的问题。");ObjectMapper objectMapper = new ObjectMapper();// 建立文档client.prepareIndex("blog2", "article", article.getId().toString())//.setSource(objectMapper.writeValueAsString(article)).get();.setSource(objectMapper.writeValueAsString(article).getBytes(), XContentType.JSON).get();//释放资源client.close();
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-G6uLiECo-1638370275539)(image/7.png)]
1.5 查询文档操作
1.5.1关键词查询
@Test
public void testTermQuery() throws Exception{//1、创建es客户端连接对象Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));//2、设置搜索条件SearchResponse searchResponse = client.prepareSearch("blog2").setTypes("article").setQuery(QueryBuilders.termQuery("content", "搜索")).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.getSource().get("title"));}//4、释放资源client.close();}
2.5.2 字符串查询
@Test
public void testStringQuery() throws Exception{//1、创建es客户端连接对象Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));//2、设置搜索条件SearchResponse searchResponse = client.prepareSearch("blog2").setTypes("article").setQuery(QueryBuilders.queryStringQuery("搜索")).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.getSource().get("title"));}//4、释放资源client.close();}
2.5.2 使用文档ID查询文档
@Testpublic void testIdQuery() throws Exception {//client对象为TransportClient对象SearchResponse response = client.prepareSearch("blog1").setTypes("article")//设置要查询的id.setQuery(QueryBuilders.idsQuery().addIds("test002"))//执行查询.get();//取查询结果SearchHits searchHits = response.getHits();//取查询结果总记录数System.out.println(searchHits.getTotalHits());Iterator<SearchHit> hitIterator = searchHits.iterator();while(hitIterator.hasNext()) {SearchHit searchHit = hitIterator.next();//打印整行数据System.out.println(searchHit.getSourceAsString());}}
2.6 查询文档分页操作
2.6.1 批量插入数据
@Test
//批量插入100条数据
public void test9() throws Exception{// 创建Client连接对象Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));ObjectMapper objectMapper = new ObjectMapper();for (int i = 1; i <= 100; i++) {// 描述json 数据Article article = new Article();article.setId(i);article.setTitle(i + "搜索工作其实很快乐");article.setContent(i+ "我们希望我们的搜索解决方案要快,我们希望有一个零配置和一个完全免费的搜索模式,我们希望能够简单地使用JSON通过HTTP的索引数据,我们希望我们的搜索服务器始终可用,我们希望能够一台开始并扩展到数百,我们要实时搜索,我们要简单的多租户,我们希望建立一个云的解决方案。Elasticsearch旨在解决所有这些问题和更多的问题。");// 建立文档client.prepareIndex("blog2", "article", article.getId().toString())//.setSource(objectMapper.writeValueAsString(article)).get();.setSource(objectMapper.writeValueAsString(article).getBytes(),XContentType.JSON).get();}//释放资源client.close();
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wX830A1N-1638370275540)(image/12.png)]
2.6.2 分页查询
@Test
//分页查询
public void test10() throws Exception{// 创建Client连接对象Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));// 搜索数据SearchRequestBuilder searchRequestBuilder = client.prepareSearch("blog2").setTypes("article").setQuery(QueryBuilders.matchAllQuery());//默认每页10条记录// 查询第2页数据,每页20条//setFrom():从第几条开始检索,默认是0。//setSize():每页最多显示的记录数。searchRequestBuilder.setFrom(0).setSize(5);SearchResponse searchResponse = searchRequestBuilder.get();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("id:" + searchHit.getSource().get("id"));System.out.println("title:" + searchHit.getSource().get("title"));System.out.println("content:" + searchHit.getSource().get("content"));System.out.println("-----------------------------------------");}//释放资源client.close();
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sRDpq6nS-1638370275542)(image/13.png)]
2.7 查询结果高亮操作
2.7.1 什么是高亮显示
在进行关键字搜索时,搜索出的内容中的关键字会显示不同的颜色,称之为高亮
百度搜索关键字"传智播客"
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZJj8nMfB-1638370275543)(image/14.png)]
京东商城搜索"笔记本"
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uRjplTEq-1638370275544)(image/15.png)]
2.7.2 高亮显示的html分析
通过开发者工具查看高亮数据的html代码实现:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rMiLOtEW-1638370275545)(image/16.png)]
ElasticSearch可以对查询出的内容中关键字部分进行标签和样式的设置,但是你需要告诉ElasticSearch使用什么标签对高亮关键字进行包裹
2.7.3 高亮显示代码实现
@Test
//高亮查询
public void test11() throws Exception{// 创建Client连接对象Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));// 搜索数据SearchRequestBuilder searchRequestBuilder = client.prepareSearch("blog2").setTypes("article").setQuery(QueryBuilders.termQuery("title", "搜索"));//设置高亮数据HighlightBuilder hiBuilder=new HighlightBuilder();hiBuilder.preTags("<font style='color:red'>");hiBuilder.postTags("</font>");hiBuilder.field("title");searchRequestBuilder.highlighter(hiBuilder);//获得查询结果数据SearchResponse searchResponse = searchRequestBuilder.get();//获取查询结果集SearchHits searchHits = searchResponse.getHits();System.out.println("共搜到:"+searchHits.getTotalHits()+"条结果!");//遍历结果for(SearchHit hit:searchHits){System.out.println("String方式打印文档搜索内容:");System.out.println(hit.getSourceAsString());System.out.println("Map方式打印高亮内容");System.out.println(hit.getHighlightFields());System.out.println("遍历高亮集合,打印高亮片段:");Text[] text = hit.getHighlightFields().get("title").getFragments();for (Text str : text) {System.out.println(str);}}//释放资源client.close();
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oo40ZXsK-1638370275546)(image/17.png)]
第三章 Spring Data ElasticSearch 使用
3.1 Spring Data ElasticSearch简介
3.1.1 什么是Spring Data
Spring Data是一个用于简化数据库访问,并支持云服务的开源框架。其主要目标是使得对数据的访问变得方便快捷,并支持map-reduce框架和云计算数据服务。 Spring Data可以极大的简化JPA的写法,可以在几乎不用写实现的情况下,实现对数据的访问和操作。除了CRUD外,还包括如分页、排序等一些常用的功能。
Spring Data的官网:http://projects.spring.io/spring-data/
Spring Data常用的功能模块如下:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NvpcAooJ-1638370275547)(image\18.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-r8dhZOOs-1638370275548)(image\19.png)]
3.1.2 什么是Spring Data 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/
3.2 Spring Data ElasticSearch入门
1)导入Spring Data ElasticSearch坐标
<?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.itheima</groupId><artifactId>itheima_elasticsearch_demo3</artifactId><version>1.0-SNAPSHOT</version><dependencies><dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>5.6.8</version></dependency><dependency><groupId>org.elasticsearch.client</groupId><artifactId>transport</artifactId><version>5.6.8</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-to-slf4j</artifactId><version>2.9.1</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.24</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-simple</artifactId><version>1.7.21</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.12</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.8.1</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.8.1</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.8.1</version></dependency><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-elasticsearch</artifactId><version>3.0.5.RELEASE</version><exclusions><exclusion><groupId>org.elasticsearch.plugin</groupId><artifactId>transport-netty4-client</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.0.4.RELEASE</version></dependency></dependencies></project>
2)创建applicationContext.xml配置文件,引入elasticsearch命名空间
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/data/elasticsearchhttp://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd"></beans>
3)编写实体Article
package com.itheima.domain;public 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;}@Overridepublic String toString() {return "Article [id=" + id + ", title=" + title + ", content=" + content + "]";}}
4)编写Dao
package com.itheima.dao;import com.itheima.domain.Article;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;@Repository
public interface ArticleRepository extends ElasticsearchRepository<Article, Integer> {}
5)编写Service
package com.itheima.service;import com.itheima.domain.Article;public interface ArticleService {public void save(Article article);}
package com.itheima.service.impl;import com.itheima.dao.ArticleRepository;
import com.itheima.domain.Article;
import com.itheima.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class ArticleServiceImpl implements ArticleService {@Autowiredprivate ArticleRepository articleRepository;public void save(Article article) {articleRepository.save(article);}}
6) 配置applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/data/elasticsearchhttp://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd"><!-- 扫描Dao包,自动创建实例 --><elasticsearch:repositories base-package="com.itheima.dao"/><!-- 扫描Service包,创建Service的实体 --><context:component-scan base-package="com.itheima.service"/><!-- 配置elasticSearch的连接 --><!-- 配置elasticSearch的连接 --><elasticsearch:transport-client id="client" cluster-nodes="localhost:9300" cluster-name="my-elasticsearch"/><!-- ElasticSearch模版对象 --><bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate"><constructor-arg name="client" ref="client"></constructor-arg></bean></beans>
7)配置实体
基于spring data elasticsearch注解配置索引、映射和实体的关系
package com.itheima.domain;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 文档对象 (索引信息、文档类型 )
@Document(indexName="blog3",type="article")
public class Article {//@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;}@Overridepublic String toString() {return "Article [id=" + id + ", title=" + title + ", content=" + content + "]";}}
其中,注解解释如下:
@Document(indexName="blob3",type="article"):indexName:索引的名称(必填项)type:索引的类型
@Id:主键的唯一标识
@Field(index=true,analyzer="ik_smart",store=true,searchAnalyzer="ik_smart",type = FieldType.text)index:是否设置分词analyzer:存储时使用的分词器searchAnalyze:搜索时使用的分词器store:是否存储type: 数据类型
8)创建测试类SpringDataESTest
package com.itheima.test;import com.itheima.domain.Article;
import com.itheima.service.ArticleService;
import org.elasticsearch.client.transport.TransportClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class SpringDataESTest {@Autowiredprivate ArticleService articleService;@Autowiredprivate TransportClient client;@Autowiredprivate ElasticsearchTemplate elasticsearchTemplate;/**创建索引和映射*/@Testpublic void createIndex(){elasticsearchTemplate.createIndex(Article.class);elasticsearchTemplate.putMapping(Article.class);}/**测试保存文档*/@Testpublic 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项目提供集成搜索引擎");articleService.save(article);}}
3.3 Spring Data ElasticSearch的常用操作
3.3.1 增删改查方法测试
package com.itheima.service;import com.itheima.domain.Article;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;public interface ArticleService {//保存public void save(Article article);//删除public void delete(Article article);//查询全部public Iterable<Article> findAll();//分页查询public Page<Article> findAll(Pageable pageable);}
package com.itheima.service.impl;import com.itheima.dao.ArticleRepository;
import com.itheima.domain.Article;
import com.itheima.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;@Service
public class ArticleServiceImpl implements ArticleService {@Autowiredprivate ArticleRepository articleRepository;public void save(Article article) {articleRepository.save(article);}public void delete(Article article) {articleRepository.delete(article);}public Iterable<Article> findAll() {Iterable<Article> iter = articleRepository.findAll();return iter;}public Page<Article> findAll(Pageable pageable) {return articleRepository.findAll(pageable);}
}
package com.itheima.test;import com.itheima.domain.Article;
import com.itheima.service.ArticleService;
import org.elasticsearch.client.transport.TransportClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class SpringDataESTest {@Autowiredprivate ArticleService articleService;@Autowiredprivate TransportClient client;@Autowiredprivate ElasticsearchTemplate elasticsearchTemplate;/**创建索引和映射*/@Testpublic void createIndex(){elasticsearchTemplate.createIndex(Article.class);elasticsearchTemplate.putMapping(Article.class);}/**测试保存文档*/@Testpublic 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项目提供集成搜索引擎");articleService.save(article);}/**测试保存*/@Testpublic void save(){Article article = new Article();article.setId(1001);article.setTitle("elasticSearch 3.0版本发布");article.setContent("ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口");articleService.save(article);}/**测试更新*/@Testpublic void update(){Article article = new Article();article.setId(1001);article.setTitle("elasticSearch 3.0版本发布...更新");article.setContent("ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口");articleService.save(article);}/**测试删除*/@Testpublic void delete(){Article article = new Article();article.setId(1001);articleService.delete(article);}/**批量插入*/@Testpublic void save100(){for(int i=1;i<=100;i++){Article article = new Article();article.setId(i);article.setTitle(i+"elasticSearch 3.0版本发布..,更新");article.setContent(i+"ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口");articleService.save(article);}}/**分页查询*/@Testpublic void findAllPage(){Pageable pageable = PageRequest.of(1,10);Page<Article> page = articleService.findAll(pageable);for(Article article:page.getContent()){System.out.println(article);}}
}
3.3.2 常用查询命名规则
关键字 | 命名规则 | 解释 | 示例 |
---|---|---|---|
and | findByField1AndField2 | 根据Field1和Field2获得数据 | findByTitleAndContent |
or | findByField1OrField2 | 根据Field1或Field2获得数据 | findByTitleOrContent |
is | findByField | 根据Field获得数据 | findByTitle |
not | findByFieldNot | 根据Field获得补集数据 | findByTitleNot |
between | findByFieldBetween | 获得指定范围的数据 | findByPriceBetween |
lessThanEqual | findByFieldLessThan | 获得小于等于指定值的数据 | findByPriceLessThan |
3.3.3 查询方法测试
1)dao层实现
package com.itheima.dao;import com.itheima.domain.Article;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import java.util.List;public interface ArticleRepository extends ElasticsearchRepository<Article, Integer> {//根据标题查询List<Article> findByTitle(String condition);//根据标题查询(含分页)Page<Article> findByTitle(String condition, Pageable pageable);
}
2)service层实现
public interface ArticleService {//根据标题查询List<Article> findByTitle(String condition);//根据标题查询(含分页)Page<Article> findByTitle(String condition, Pageable pageable);
}
package com.itheima.service.impl;import com.itheima.dao.ArticleRepository;
import com.itheima.domain.Article;
import com.itheima.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class ArticleServiceImpl implements ArticleService {@Autowiredprivate ArticleRepository articleRepository;public List<Article> findByTitle(String condition) {return articleRepository.findByTitle(condition);}public Page<Article> findByTitle(String condition, Pageable pageable) {return articleRepository.findByTitle(condition,pageable);}}
3)测试代码
package com.itheima.test;import com.itheima.domain.Article;
import com.itheima.service.ArticleService;
import org.elasticsearch.client.transport.TransportClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.util.List;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class SpringDataESTest {@Autowiredprivate ArticleService articleService;@Autowiredprivate TransportClient client;@Autowiredprivate ElasticsearchTemplate elasticsearchTemplate;/**条件查询*/@Testpublic void findByTitle(){String condition = "版本";List<Article> articleList = articleService.findByTitle(condition);for(Article article:articleList){System.out.println(article);}}/**条件分页查询*/@Testpublic void findByTitlePage(){String condition = "版本";Pageable pageable = PageRequest.of(2,10);Page<Article> page = articleService.findByTitle(condition,pageable);for(Article article:page.getContent()){System.out.println(article);}}}
###3.3.4使用Elasticsearch的原生查询对象进行查询。
@Testpublic void findByNativeQuery() {//创建一个SearchQuery对象SearchQuery searchQuery = new NativeSearchQueryBuilder()//设置查询条件,此处可以使用QueryBuilders创建多种查询.withQuery(QueryBuilders.queryStringQuery("备份节点上没有数据").defaultField("title"))//还可以设置分页信息.withPageable(PageRequest.of(1, 5))//创建SearchQuery对象.build();//使用模板对象执行查询elasticsearchTemplate.queryForList(searchQuery, Article.class).forEach(a-> System.out.println(a));}
ElasticSearch第二天相关推荐
- Elasticsearch 第二天
Elasticsearch day02 1 Elasticsearch高级检索DSL检索 准备测试数据: #删除索引 DELETE /ems #添加索引并设置类型 PUT /ems { "m ...
- elasticsearch 第二篇(配置篇)
配置 在es启动之前可以通过设置启动命令行启动参数.环境变量.文件等方式优化和配置es进行参数 环境变量 名称 示例 说明 ES_MIN_MEM 256M 用于配置java进程分配的最小内存 ES_M ...
- ElasticSearch第一天
ElasticSearch第一天 学习目标: 能够理解ElasticSearch的作用 能够安装ElasticSearch服务 能够理解ElasticSearch的相关概念 能够使用Postman发送 ...
- 史上最简单的Elasticsearch教程:SpringBoot集成Elasticsearch 实时流量监测平台
SpringBoot集成Elasticsearch 实时流量监测平台 目录: 第一章:初尝 Elasticsearch 第二章:玩转 Kibana 第三章:开发原生 Elasticsearch 案例 ...
- ElasticSearch基础:从倒排索引说起,快速认知ES
ElasticSearch基础:从倒排索引说起,快速认知ES 1 ElasticSearch认知 1.1 关于搜索 1.2 倒排索引 1.3 Lucene 1.4 ES基本概念 1.5 ES集群概念 ...
- ElasticSearch使用教程、设计到实战
ElasticSearch 倒排索引 Logstash 有用的 Logstash 链接 Logstash 频道博客文章 https://blog.csdn.net/ubuntutouch/catego ...
- ES(elasticsearch) - kibana导出csv
文章目录 es系列导航 前言 1.条件过滤 2.下载 3.常见问题 1.进行条件过滤后,没有对应的数据进行展示: 2.kibana 导出失败,completed max size reached 3. ...
- Open Source
资源来源于http://www.cnblogs.com/Leo_wl/category/246424.html RabbitMQ 安装与使用 摘要: RabbitMQ 安装与使用 前言 吃多了拉就是队 ...
- ElasticSearch--核心总结
ElasticSearch 第一章 ElasticSearch简介 1.1 什么是ElasticSearch Elaticsearch,简称为ES, ES是一个开源的高扩展的分布式全文检索引擎服务器, ...
最新文章
- Java七步创建以JDBC连接数据库的程序
- RabbitMQ 延迟队列,太实用了!
- 第二章 spring
- A. Boredom【DP】
- 注意我写的OTA短信同步设置的代码有很多问题
- Linux下统计局域网流量
- Python查找指定文件
- 面试项目 java-服务端 18h58
- 大厂都在拆中台了,为什么我们还死磕到底?
- sh文件进行qsub提交任务到远程服务器训练
- 【Luogu2085】最小函数值(优先队列)
- python用程序说爱你_用python写一个聊天小程序!和女朋友的专属聊天工具!
- Java之ApiPost工具
- oracle 职业规划,数据库工程师的职业规划
- 浏览器首页被恶意篡改
- html打包成apk wex5,WeX5打包部署学习
- 谈胶印机供水装置调节的技巧
- 调试的时候没有在断点处停止的原因
- QGIS二次开发:加载XYZ Tiles形式的瓦片地图
- 【开发工具】Linux环境下JDK安装(无错完整)
热门文章
- ACM练习 链表排序 II 【WA】
- Leet Code OJ 4. Median of Two Sorted Arrays [Difficulty: Hard]
- 数据结构——排序算法(含动态图片)
- 06.search_shard_api操作
- 笛卡尔树 (25 分)笛卡尔树是一种特殊的二叉树,其结点包含两个关键字K1和K2。首先笛卡尔树是关于K1的二叉搜索树,即结点左子树的所有K1值都比该结点的K1值小,右子树则大。其次所有结点的K2关键字
- ctype.h(cctype) 头文件函数大全
- 家用电脑配置_家用电脑无需太高配置,不要听电脑店瞎忽悠,2500元机子够用了!...
- 现实生活中常用的动态路由OSPF(单区)
- wamp 使用mysql_PHP当中如何使用Wampserver连接到Mysql数据库以及怎样使用
- python自动下载app_APP自动化之安装Python(类库)环境