前面的章节使用curl的方式去添加修改我们的es数据,然后来看看Java后台是怎么来操作es数据。
一、环境准备
没有环境的朋友,请先参考前面提到的安装方式进行安装。如果有安装不成功者,可以联系我。
文章最后我会把个人微信提供下,欢迎跟各位Java友友一起交流成长。
pom.xml
4.0.0
com.guo.elasticsearch
ElasticsearchHandler
war
0.0.1-SNAPSHOT
ElasticsearchHandler Maven Webapp
http://maven.apache.org
junit
junit
3.8.1
test
org.elasticsearch
elasticsearch
6.1.1
org.elasticsearch.client
transport
6.1.1
org.apache.logging.log4j
log4j-core
2.9.1
org.apache.logging.log4j
log4j-api
2.9.1
org.slf4j
slf4j-api
1.7.21
ElasticsearchHandler
有的朋友习惯idea也可以用这个,相信Java友友这个应该都比较熟悉的,我创建的是maven项目,所以也需要maven插件的。也可以不用maven,那就需要自己去找jar包了。这些相信有基础的Java友友一般都会,就不一一介绍了。
二、代码准备
1.实体类
package com.es;
/**
*
* 功能描述: 实体类
* @author gqh
* @date 2019年2月3日
*/
public class KnowledgeVO {
private String id;
private String title;
private String keyword;
private String source;
private String version;
private String content;
private String creatorName;
private String createTime;
private String indexId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getCreatorName() {
return creatorName;
}
public void setCreatorName(String creatorName) {
this.creatorName = creatorName;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getIndexId() {
return indexId;
}
public void setIndexId(String indexId) {
this.indexId = indexId;
}
}
简单的弄了一个实体类。
2.转换es–json工具类
package com.es;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
/**
* 功能描述:用于对象转换json
* @author gqh
* @date 2019年2月3日
*/
public class JsonUtil {
public static String objJsonDate(KnowledgeVO vo) {
String jsonData = null;
try {
//使用XContentBuilder创建json数据
XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();
jsonBuilder.startObject()
.field("id", vo.getId())
.field("title", vo.getTitle())
.field("keyword", vo.getKeyword())
.field("source", vo.getSource())
.field("version", vo.getVersion())
.field("content", vo.getContent())
.field("creatorName",vo.getCreatorName())
.field("createTime",vo.getCreateTime())
.endObject();
jsonData = jsonBuilder.string();
} catch (Exception e) {
e.printStackTrace();
}
return jsonData;
}
}
3.客户端连接
/**
*
* 功能描述:创建客户端连接ES服务
* @return
*/
public static TransportClient getClient() {
try {
String ipAddress = "192.168.1.120";
int port = 9300;
//程序中更改集群结点名称 并且设置client.transport.sniff为true来使客户端去嗅探整个集群的状态
Settings settings = Settings.builder()
.put("client.transport.sniff",true)
.build();
client = new PreBuiltTransportClient(settings);
client.addTransportAddress(new TransportAddress(InetAddress.getByName(ipAddress), port));
} catch (UnknownHostException e) {
e.printStackTrace();
}
return client;
}
没有用到集群方式,但是我把集群的方式也加入了。
4.基本属性
private static TransportClient client = null;
private static String indexName = "knowledge";
private static String indexType = "knowledge";
private static Logger logger = LoggerFactory.getLogger(ElasticSearchHandler.class);
5.添加索引
/**
*
* 功能描述:添加索引数据
* @param vo
* @return
*/
public synchronized static String createIndex(KnowledgeVO vo) {
String doc_id = "";
try {
String jsonDate = JsonUtil.objJsonDate(vo);
IndexRequestBuilder requestBuilder = getClient().prepareIndex(indexName,indexType);
IndexResponse ir = requestBuilder.setSource(jsonDate,XContentType.JSON).execute().actionGet();
String index_type = ir.getType();
String index_name = ir.getIndex();
long version = ir.getVersion();
doc_id = ir.getId();
logger.info("索引名:"+index_name);
logger.info("索引类型:"+index_type);
logger.info("索引版本号:"+version);
logger.info("doc_id:"+doc_id);
} catch (Exception e) {
e.printStackTrace();
logger.info("哇哦,添加索引失败了");
}
return doc_id;
}
6.更新索引
/**
* 功能描述:更新索引
*/
public static void updateIndex(KnowledgeVO vo) {
try {
UpdateRequest uRequest = new UpdateRequest();
uRequest.index(indexName);
uRequest.type(indexType);
uRequest.id(vo.getIndexId());
uRequest.doc("{\"title\":\"测试数据\"}", XContentType.JSON);
getClient().update(uRequest).get();
} catch (Exception e) {
e.printStackTrace();
logger.info("哇哦,更新索引失败了");
}
}
7.查询
/**
* 功能描述:查询
* @return
*/
public static List searcher(Map pmap,int from, int size ) {
List list = new ArrayList();
BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
String searchWord = pmap.get("searchWord");
queryBuilder
.should(QueryBuilders.wildcardQuery("title", "*"+searchWord+"*"))
.should(QueryBuilders.queryStringQuery("content:"+searchWord).defaultOperator(Operator.OR))
.should(QueryBuilders.queryStringQuery("fileContent:"+searchWord).defaultOperator(Operator.OR))
.should(QueryBuilders.queryStringQuery("keyword:"+searchWord).defaultOperator(Operator.OR));
queryBuilder.minimumShouldMatch(1);
SearchResponse searchResponse = getClient().prepareSearch(indexName).setTypes(indexType)
.setQuery(queryBuilder).setFrom(from).setSize(size)
.setExplain(true)
.execute()
.actionGet();
SearchHits hits = searchResponse.getHits();
long totalHits = hits.getTotalHits();
logger.info("查询到记录数=" + totalHits);
SearchHit[] searchHists = hits.getHits();
if(searchHists.length > 0) {
for(SearchHit hit:searchHists){
logger.debug("hit.getId() =" + hit.getId());
String id = (String)hit.getSourceAsMap().get("id");
String title = (String) hit.getSourceAsMap().get("title");
String keyword = (String)hit.getSourceAsMap().get("keyword");
String source = (String) hit.getSourceAsMap().get("source");
String version = (String) hit.getSourceAsMap().get("version");
String contents = (String) hit.getSourceAsMap().get("content");
KnowledgeVO vo = new KnowledgeVO();
vo.setId(id);
vo.setTitle(title);
vo.setKeyword(keyword);
vo.setSource(source);
vo.setVersion(version);
vo.setContent(contents);
list.add(vo);
}
}
return list;
}
我把返回的数据都加入list当中,后续有做web的时候,可以用来做展示。titile查询我加入一个类似于sql里面like查询的功能,区别于其他的普通查询。还有一些特殊的查询没有一一罗列,友友们可以自行学习。
8.删除索引
/**
* 功能描述:删除索引
* @param knowId
*/
public static void DelIndex(String id) {
try {
QueryBuilder queryBuilder = QueryBuilders.termQuery("id", id);
DeleteByQueryAction.INSTANCE.newRequestBuilder(getClient())
.filter(queryBuilder)
.source(indexName)
.get();
} catch (Exception e) {
e.printStackTrace();
logger.info("哇哦,删除索引失败了");
}
}
9.测试类
public static void main(String[] args){
try{
//elasticsearch6.1.1版本测试
/*
添加方法
KnowledgeVO vo = new KnowledgeVO();
vo.setId("1234567");
vo.setTitle("软件大集合");
vo.setKeyword("Java");
vo.setSource("Oracle");
vo.setContent("Java数据");
vo.setVersion("1.0");
vo.setCreatorName("某某某");
vo.setIndexId("AWizBU0ygy2IhqmdsetP");
String indexId = createIndex(vo);
System.out.println("文档id===="+indexId);*/
/*
更新方法(记得放入索引id)
String indexId = "AWizBU0ygy2IhqmdsetP";
updateIndex(vo);
*/
/*
查询方法
Map param = new HashMap();
param.put("searchWord", "王者");
List searcher = searcher(param,0,10);
for(int i=0;i
Java友友可以自行去扩展每个方法根据自己需要的结果去处理。