本文主要讲述如何使用java-maven架构实现ElasticSearch增删改查,分页查询,高亮处理,以及创建Index,Mapping的方式
<dependencies>
<dependency>
<groupId>org.elasticsearch.clientgroupId>
<artifactId>transportartifactId>
<version>5.6.8version>
dependency>
<dependency>
<groupId>org.apache.logging.log4jgroupId>
<artifactId>log4j-to-slf4jartifactId>
<version>2.9.1version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>1.7.24version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-simpleartifactId>
<version>1.7.21version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.12version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.10version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
<version>2.8.1version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.8.1version>
dependency>
dependencies>
Article实体类
package pojo;
/**
* @ Description
* @ auther 宁宁小可爱
* @ create 2020-07-31 11:06
*/
public class Article {
private Long id;
private String title;
private String content;
public Long getId() {
return id;
}
public void setId(Long 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;
}
}
创建Index和Mapping实现代码
package com.jwc.test;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;
import pojo.Article;
import java.net.InetAddress;
/**
* @ Description
* @ auther 宁宁小可爱
* @ create 2020-07-31 9:06
*/
public class ES2Test {
private String host = "127.0.0.1";
private int port = 9300;
/*
* 使用管理权限,单独创建索引
* */
@Test
public void createIndex()throws Exception{
// 创建客户端对象
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host),port));
// 使用管理权限创建索引
CreateIndexResponse response = transportClient.admin().indices().prepareCreate("blog2").get();
System.out.println(response.isShardsAcked());
System.out.println(response.isAcknowledged());
// 关闭资源
transportClient.close();
}
/*
* 使用管理权限,删除索引
* */
@Test
public void deleteIndex()throws Exception{
// 创建客户端对象
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host),port));
// 使用管理权限删除索引 使用字符串方式
DeleteIndexResponse response = transportClient.admin().indices().prepareDelete("blog2").get();
// 使用管理权限删除索引 使用对象方式
DeleteIndexResponse blog2 = transportClient.admin().indices().delete(new DeleteIndexRequest("blog2")).get();
// 返回执行结果
System.out.println(response.isAcknowledged());
// 关闭资源
transportClient.close();
}
/*
* 创建Mapping映射
* */
@Test
public void createMapping()throws Exception{
// 创建文档格式 mapping
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
.startObject()
.startObject("article")
.startObject("properties")
.startObject("id")
.field("type", "long")
.field("store", true)
.endObject()
.startObject("title")
.field("type", "text")
.field("analyzer", "ik_max_word")
.field("store", true)
.endObject()
.startObject("content")
.field("type", "text")
.field("analyzer", "ik_max_word")
.field("store", true)
.endObject()
.endObject()
.endObject()
.endObject();
// 封装Mapping请求
PutMappingRequest putMappingRequest = Requests.putMappingRequest("blog2").type("article").source(xContentBuilder);
// 创建客户端对象
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host),port));
// 判断要添加Mapping映射的索引是否存在
IndicesExistsResponse indicesResponse = transportClient.admin().indices().exists(new IndicesExistsRequest("blog2")).get();
// 如果不存在 那么创建索引
if (!indicesResponse.isExists()){
CreateIndexResponse blog2 = transportClient.admin().indices().prepareCreate("blog2").get();
// 输出索引是否执行成功返回值
System.out.println(blog2.isAcknowledged());
}
// 创建Mapping 映射
PutMappingResponse putMappingResponse = transportClient.admin().indices().putMapping(putMappingRequest).get();
// 关闭资源
transportClient.close();
}
}
private String host = "127.0.0.1";
private int port = 9300;
/*
* 使用实体类生成DOC文档
* */
@Test
public void creatDocByBean()throws Exception{
// 创建客户端对象
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host),port));
// 创建实体类 Article
Article article = new Article();
article.setId(2L);
article.setTitle("ElasticSearch是一个基于Lucene的搜索服务器");
article.setContent("提供了一个分布式多用户能力的全文搜索引擎");
// 把对象转换为Json字符串
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = objectMapper.writeValueAsString(article);
// 使用客户端执行命令
IndexResponse indexResponse = transportClient.prepareIndex("blog", "article", String.valueOf(article.getId())).setSource(jsonStr).get();
// 关闭资源
transportClient.close();
}
private String host = "127.0.0.1";
private int port = 9300;
/*
* 使用实体类删除DOC文档
* */
@Test
public void deleteDoc() throws Exception {
// 创建客户端对象
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
// 创建实体类 Article
Article article = new Article();
article.setId(1L);
// 使用Object方式修改DOC 这里的Request对象最后一位参数是指 文档的唯一标识
transportClient.prepareDelete("blog", "article", String.valueOf(article.getId())).get();
// 关闭资源
transportClient.close();
}
private String host = "127.0.0.1";
private int port = 9300;
/*
* 使用实体类修改DOC文档
* */
@Test
public void updateDocByBean()throws Exception{
// 创建客户端对象
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host),port));
// 创建实体类 Article
Article article = new Article();
article.setId(2L);
article.setTitle("一个基于Lucene的搜索服务器");
article.setContent("一个分布式多用户能力的全文搜索引擎");
// 把对象转换为Json字符串
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = objectMapper.writeValueAsString(article);
// 使用客户端执行修改命令
// UpdateResponse updateResponse = transportClient.prepareUpdate("blog", "article", String.valueOf(article.getId())).setDoc(jsonStr).get();
// 使用Object方式修改DOC 这里的Request对象最后一位参数是指 文档的唯一标识
UpdateResponse objectResponse = transportClient.update(new UpdateRequest("blog","article",String.valueOf(article.getId())).doc(jsonStr)).get();
// 关闭资源
transportClient.close();
}
package com.jwc.test;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;
import pojo.Article;
import java.net.InetAddress;
/**
* @ Description
* @ auther 宁宁小可爱
* @ create 2020-07-31 9:06
*/
public class ES2Page {
private String host = "127.0.0.1";
private int port = 9300;
/*
* 批量添加数据
* */
@Test
public void addBatch()throws Exception{
// 创建客户端对象
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host),port));
for (int i = 1 ; i<101 ;i++){
// 创建实体类 Article
Article article = new Article();
article.setId(Long.parseLong(String.valueOf(i)));
article.setTitle("一个基于Lucene的搜索服务器"+i);
article.setContent("一个分布式多用户能力的全文搜索引擎"+i);
// 把对象转换为Json字符串
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = objectMapper.writeValueAsString(article);
// 添加数据
transportClient.prepareIndex("blog2","article",String.valueOf(article.getId())).setSource(jsonStr).get();
// 关闭资源
}
transportClient.close();
}
/*
* 分页查询
* */
@Test
public void testPage()throws Exception{
// 创建客户端对象
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host),port));
// 查询
SearchRequestBuilder searchRequestBuilder = transportClient
.prepareSearch("blog2")
.setTypes("article")
.setQuery(QueryBuilders.matchAllQuery());
// 处理分页
searchRequestBuilder.setFrom(0); // 设置从那一条开始
searchRequestBuilder.setSize(5); // 设置每页显示条数
searchRequestBuilder.addSort("id", SortOrder.ASC); // 设置排序规则
// 执行查询命令
SearchResponse searchResponse = searchRequestBuilder.get();
// 获取命中的条数
SearchHits hits = searchResponse.getHits();
// 输出总记录数
System.out.println(hits.getTotalHits());
// 循环展示
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
// 关闭资源
transportClient.close();
}
}
package com.jwc.test;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;
import pojo.Article;
import javax.sound.midi.Soundbank;
import java.net.InetAddress;
/**
* @ Description
* @ auther 宁宁小可爱
* @ create 2020-07-31 9:06
*/
public class ES2HightLight {
private String host = "127.0.0.1";
private int port = 9300;
/*
* 处理高亮
* */
@Test
public void testHighLight() throws Exception {
// 创建客户端对象
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
SearchRequestBuilder searchRequestBuilder = transportClient
.prepareSearch("blog2")
.setTypes("article")
// 词条查询符合高亮查询基本要求
.setQuery(QueryBuilders.termQuery("title","基于"));
// 处理高亮字段
HighlightBuilder highLight = new HighlightBuilder();
// 添加前缀
highLight.preTags("");
// 添加字段
highLight.field("title");
// 添加后缀
highLight.postTags("");
// 设置高亮
searchRequestBuilder.highlighter(highLight);
// 执行命令
SearchResponse searchResponse = searchRequestBuilder.get();
// 获取高亮查询结果
SearchHits hits = searchResponse.getHits();
for (SearchHit hit : hits) {
// 获取高亮字段
Text[] titles = hit.getHighlightFields().get("title").fragments();
for (Text title : titles) {
System.out.println(title.toString());
}
}
// 关闭资源
transportClient.close();
}
}