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 ...
随机推荐
- xcode4.3.2 arc模式下导入非arc的文件 转
在arc模式下,我们经常会用到非arc的类库,此时我们可以在Compile Sources下对该文件进行编辑加入 -fno-objc-arc 如图中所示,就可以使用非arc的类库了 转:htt ...
- hue耗流量优化
ps: 使用的hue版本为 hue-3.10.0 一.[jobbrowser刷流量] 基本一分钟刷新一次,执行GET /jobbrowser/ [17/Apr/2017 14:46:26 +0800] ...
- dao层的泛型实现(2种方法)
一: package com.wzs.test2.dao; import java.util.List; public interface CommonDAO { public <T> v ...
- UT-Austin大学在Image search and large-scale retrieval方面的一系列papers
WhittleSearch: Interactive Image Search with Relative Attribute Feedback. A. Kovashka, D. Parikh, a ...
- 基尼系数(Gini coefficient),洛伦茨系数
20世纪初意大利经济学家基尼,于1922年提出的定量测定收入分配差异程度的指标.它是根据洛伦茨曲线找出了判断分配平等程度的指标(如下图). 设实际收入分配曲线和收入分配绝对平等曲线之间的面积为A,实际 ...
- scala编程第17章学习笔记(4)——元组
元组可以把固定数量的条目组合在一起以便于作为整体传送.不像数组或列表,元组可以保存不同类型的对象. 元组常用来返回方法的多个值.例如,下面的方法找到集合中的最长单词并返回它的索引: scala> ...
- GPGPU OpenCL 获取kernel函数编译信息
使用OpenCL编程时,kernel写成一个单独的文件或者将文件内容保存在一个string中.可以使用clBuildProgram对kernel进行编译链接(compiles & links) ...
- Jungle Roads_hdu_1301(prim算法)
Jungle Roads Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Tot ...
- [转] ssh穿透??未验证。。。
一. SSH ProxyCommand 实践 http://www.cnblogs.com/shanpow/p/4264867.html 二. SSH穿越跳板机:一条命令跨越跳板机直接登陆远程计算机 ...
- 如何用命令行管理windows记住的用户名和密码
cmdkey https://technet.microsoft.com/en-us/library/cc754243.aspx