Java下Elasticsearh应用指南
简介
本文针对在Java下操作elasticsearch给出应用示例,主要涉及创建连接,构建索引以及检索数据3个部分。
环境
1)elasticsearch2.4.4,
2)jdk1.8。
客户端连接
import java.net.InetAddress;
import java.net.UnknownHostException; import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class Client {
private static Logger logger = LoggerFactory.getLogger(Client.class);
private static Settings settings = Settings.settingsBuilder()
.put("cluster.name", "app").build(); /**
* only one address
* @param ipAddress
* @return
*/
public static TransportClient initClient(String ipAddress) {
TransportClient client = null;
try {
client = TransportClient.builder().settings(settings).build()
.addTransportAddress(new InetSocketTransportAddress(
InetAddress.getByName(ipAddress), 9300));
logger.info("client start up", ipAddress);
} catch (UnknownHostException e) {
e.printStackTrace();
logger.error(ipAddress, e.getMessage());
} return client;
} /**
* has more addresses
* @param ipAddress
* @return
*/
public static TransportClient initClient(String[] ipAddress) {
TransportClient client = null;
try {
client = TransportClient.builder().settings(settings).build();
for (String ip : ipAddress) {
client.addTransportAddress(new InetSocketTransportAddress(
InetAddress.getByName(ip), 9300));
}
} catch (UnknownHostException e) {
logger.error(ipAddress.toString(), e.getMessage());
} return client;
} public static void close(TransportClient client) {
if (client != null) {
client.close();
}
} }
创建索引
import java.util.Map; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
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.PutMappingResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Index {
private static Logger logger = LoggerFactory.getLogger(Index.class); /**
* create index before mapping
* @param client
* @param indexName
*/
public static void indexCreate(TransportClient client, String indexName) {
deleteIndex(client, indexName);
client.admin().indices()
.create(new CreateIndexRequest(indexName))
.actionGet();
} /**
* set the mapping for index
* @param client
* @param indexName
* @param docName
* @return
*/
public static PutMappingResponse indexMapping(TransportClient client, String indexName,
String docName) {
indexCreate(client, indexName);
PutMappingResponse response = client.admin().indices()
.preparePutMapping(indexName)
.setType(docName)
.setSource(getMapping(docName))
.execute()
.actionGet(); return response;
} /**
* index for target data
* @param client
* @param indexName
* @param docName
* @param data
* @return
*/
public static IndexResponse createIndexResponse(TransportClient client,
String indexName, String docName, Map<String, String> data) {
IndexResponse response = client.prepareIndex(indexName, docName)
.setSource(data)
.execute()
.actionGet(); return response;
} public static void deleteIndex(TransportClient client, String indexName) {
IndicesExistsResponse isExistsResponse = client.admin().indices()
.exists(new IndicesExistsRequest(indexName))
.actionGet();
if (isExistsResponse.isExists()) {
client.admin().indices()
.delete(new DeleteIndexRequest(indexName))
.actionGet();
}
} }
检索索引
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.lucene.index.Fields;
import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.termvectors.TermVectorsResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class Search {
private static Logger logger = LoggerFactory.getLogger(Search.class); /**
* get the search response with the index and document for keyword
* @param client
* @param indexName
* @param docName
* @param field
* @param keyword
* @return
*/
public static SearchResponse getSearchResponse(TransportClient client,
String indexName, String docName, String field, String keyword) {
SearchResponse response = client.prepareSearch(indexName)
.setTypes(docName)
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(QueryBuilders.matchQuery(field, keyword))
.setFrom(0).setSize(60).setExplain(true)
.execute()
.actionGet(); return response;
} /**
* get the terms vector for the target field
* @param client
* @param indexName
* @param docName
* @param docID
* @return
*/
public static TermVectorsResponse getTermVectorResponse(TransportClient client,
String indexName, String docName, String docID, String field) {
TermVectorsResponse response = client
.prepareTermVectors(indexName, docName, docID)
.setSelectedFields(field)
.setPositions(true)
.setOffsets(true)
.execute().actionGet();
return response;
} /**
* get the match String for target field
* @param response
* @param field
* @return
*/
public static Map<String, String> getMatchField(SearchResponse response,
String field) {
long total = 0;
Map<String, String> map = null;
if (response != null) {
SearchHits hits = response.getHits();
if (hits != null) {
total = hits.getTotalHits();
if (total > 0) {
map = new HashMap<String, String>();
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
String value = (String)hit.getSource().get(field);
String id = hit.getId();
map.put(id, value);
}
}
}
} return map;
}
}
作者:志青云集
出处:http://www.cnblogs.com/lyssym
如果,您认为阅读这篇博客让您有些收获,不妨点击一下右下角的【推荐】。
如果,您希望更容易地发现我的新博客,不妨点击一下左下角的【关注】。
如果,您对我的博客所讲述的内容有兴趣,请继续关注我的后续博客,我是【志青云集】。
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则将依法追究法律责任。
Java下Elasticsearh应用指南的更多相关文章
- Java 脚本化编程指南
Java 脚本化编程指南 Java脚本化API为谁准备? 脚本语言的一些有用的特性是: 方便:大多数脚本语言都是动态类型的.您通常可以创建新的变量,而不声明变量类型,并且您可以重用变量来存储不同类型的 ...
- Java_并发工具包 java.util.concurrent 用户指南(转)
译序 本指南根据 Jakob Jenkov 最新博客翻译,请随时关注博客更新:http://tutorials.jenkov.com/java-util-concurrent/index.html.本 ...
- 《Java性能优化权威指南》
<Java性能优化权威指南> 基本信息 原书名:Java performance 原出版社: Addison-Wesley Professional 作者: (美)Charlie Hunt ...
- Java多线程编程实战指南(核心篇)读书笔记(五)
(尊重劳动成果,转载请注明出处:http://blog.csdn.net/qq_25827845/article/details/76730459冷血之心的博客) 博主准备恶补一番Java高并发编程相 ...
- Java多线程编程实战指南(核心篇)读书笔记(四)
(尊重劳动成果,转载请注明出处:http://blog.csdn.net/qq_25827845/article/details/76690961冷血之心的博客) 博主准备恶补一番Java高并发编程相 ...
- Java多线程编程实战指南(核心篇)读书笔记(三)
(尊重劳动成果,转载请注明出处:http://blog.csdn.net/qq_25827845/article/details/76686044冷血之心的博客) 博主准备恶补一番Java高并发编程相 ...
- Java多线程编程实战指南(核心篇)读书笔记(二)
(尊重劳动成果,转载请注明出处:http://blog.csdn.net/qq_25827845/article/details/76651408冷血之心的博客) 博主准备恶补一番Java高并发编程相 ...
- Java多线程编程实战指南(核心篇)读书笔记(一)
(尊重劳动成果,转载请注明出处:http://blog.csdn.net/qq_25827845/article/details/76422930冷血之心的博客) 博主准备恶补一番Java高并发编程相 ...
- 《Java多线程编程实战指南(核心篇)》阅读笔记
<Java多线程编程实战指南(核心篇)>阅读笔记 */--> <Java多线程编程实战指南(核心篇)>阅读笔记 Table of Contents 1. 线程概念 1.1 ...
随机推荐
- NGUI 3.5教程(一)安装NGUI 3.5.8
写在前面: 网上找的NGUI教程,都是基于2.x版本号的.为了能配合教程学着做,我也是下载了各种NGUI 2.x版本号.可是在导入的时候,或多或少都报错(我用的Unity 的版本号是4.3.2).无奈 ...
- Eclipse点不出方法了
window→preferences→java→editor→Content Assist→Advanced 然后选中右上方的所有 右下方选中一个即可.
- Android图片加载框架最全解析(五),Glide强大的图片变换功能
大家好,又到了学习Glide的时间了.前段时间由于项目开发紧张,再加上后来又生病了,所以停更了一个月,不过现在终于又可以恢复正常更新了.今天是这个系列的第五篇文章,在前面四篇文章的当中,我们已经学习了 ...
- inline
inline 大学在教科书上学习过inline函数,定义为inline函数之后,会省去函数调用的开销,直接嵌套汇编代码,取代函数调用,提高效率.工作后项目中也很少用到inline来定义函数,近几天在研 ...
- json和gson的区别
json是一种数据格式,便于数据传输.存储.交换gson是一种组件库,可以把java对象数据转换成json数据格式 GSON简单处理JSON json格式经常需要用到,google提供了一个处理jso ...
- C++中new的用法及显示调用析构函数
最近被问到了C++内存池的问题,其中不免涉及到在指定内存地址调用对象构造函数以及显示调用对象析构函数的情况. C++中new的用法 new是C++中用于动态内存分配的运算符,在C语言中一般使用mall ...
- 阿里的STORM——JSTORM
看介绍文档貌似挺好:https://github.com/alibaba/jstorm 阿里拥有自己的实时计算引擎 类似于hadoop 中的MR 开源storm响应太慢 开源社区的速度完全跟不上A ...
- trapping-rain-water-ii
https://leetcode.com/problems/trapping-rain-water-ii/ // https://discuss.leetcode.com/topic/60418/ja ...
- iOS开发-多线程简介
多线程从概念上理解是指从软件或者硬件上实现多个线程并发执行的技术,简单点理解就是同一时间可以执行多个事情(比如说一边听歌一边码代码),听歌是一个线程,码代码是一个线程,如果是单核CPU的话,上面两个动 ...
- Chain of Responsibility 责任链模式 MD
责任链模式 简介 责任链模式是一种对象的行为模式.在责任链模式里,很多对象由每一个对象对其下家的引用而连接起来形成一条链,请求在这个链上[传递],直到链上的某一个对象决定处理此请求.发出这个请求的客户 ...