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
如果,您认为阅读这篇博客让您有些收获,不妨点击一下右下角的【推荐】。
如果,您希望更容易地发现我的新博客,不妨点击一下左下角的【关注】。
如果,您对我的博客所讲述的内容有兴趣,请继续关注我的后续博客,我是【志青云集】。
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则将依法追究法律责任。