elasticsearch java API 实现搜索样例

查看cluster、version:curl ‘centos1:9200‘
插入:curl -XPUT ‘http://localhost:9200/dept/employee/1‘ -d ‘{ "empname": "emp1"}‘
查看index:curl ‘centos1:9200/_cat/indices?v‘
查看1条内容:curl ‘centos1:9200/dept/employee/1?pretty‘
查看所有内容:curl ‘centos1:9200/dept/employee/_search‘
简易搜索:curl ‘centos1:9200/dept/employee/_search?empname=emp1‘
复杂搜索:curl ‘centos1:9200/dept/employee/_search?pretty‘ -d ‘{"query" : {"match" : {"empname" : "emp2"}}}‘
删除:curl -XDELETE ‘http://172.16.1.16:9200/logstash-2016.02.*‘

3.1 ES原生API连接搜索(Java,非RestFul连接而是广播)
说明:Es的集群非常简单,只要在同一个局域网内,多台服务器能互相通讯,并且cluster.name是一样的,就能自动集在一起。

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.FuzzyQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;

/* Implement ElasticSearch internal Java API (broadcast)
 * Refer
 * http://www.tuicool.com/articles/R7RVJb
 * https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-search.html
 * http://stackoverflow.com/questions/23520684/elasticsearch-java-apinonodeavailableexception-no-node-available
 * Node Transport Difference - http://www.cnblogs.com/huangfox/p/3543134.html
 * */
public class EsQuery01 {

	public static void main(String[] args) throws Exception {

		// 1. Prepare Transport
		//Client client = buildClientByNode();
		Client client = buildClientByTransport();

		// 2. Prepare Query Param
		QueryBuilder queryBuilder = buildQuery();

		// 3. Get Response
		SearchResponse response = client.prepareSearch("dept")
		        .setTypes("employee")
		        .setQuery(queryBuilder)
		        .setFrom(0).setSize(2)
		        .execute()
		        .actionGet();
		//SearchResponse response = client.prepareSearch().execute().actionGet();

		if (response != null) {
			system.out.println(response);
			for (SearchHit hit : response.getHits().getHits()) {
				System.out.print(hit.getId() + "~");
				System.out.println(hit.getSourceAsString());
			}
		} else {
			System.out.println("response null~~~");
		}
		if (client != null) {
			client.close();
		}
	}

	/* slow */
	public static Client buildClientByTransport() throws UnknownHostException {
		final String CLUSTERNAME = "es-cluster";
		String str = "192.168.56.250";
        String[] ipStr = str.split("\\.");
        byte[] ipBuf = new byte[4];
        for(int i = 0; i < 4; i++){
            ipBuf[i] = (byte)(Integer.parseInt(ipStr[i])&0xff);
        }

		Settings settings = Settings.settingsBuilder()
		        .put("cluster.name", CLUSTERNAME).build();
		Client client = TransportClient.builder().settings(settings).build()
				.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("centos1"), 9300));
				//.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByAddress(ipBuf), 9300));
		return client;
	}

	/* very slow */
	public static Client buildClientByNode() throws UnknownHostException {
		/* Run Configurations > Arguments > VM arguments, add "-Des.path.home=/appl/elasticsearch-2.1.1" */
		final String CLUSTERNAME = "es-cluster";
		Node node = NodeBuilder.nodeBuilder().settings(Settings.settingsBuilder().put("http.enabled", false)).
				clusterName(CLUSTERNAME).client(true).node();
		Client client = node.client();
		return client;
	}

	public static QueryBuilder buildQuery() {
		//TermsQueryBuilder queryBuilder = queryByIds();
		//FuzzyQueryBuilder queryBuilder = QueryBuilders.fuzzyQuery("empname", "emp");
		MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("empname", "emp2");
		//WildcardQueryBuilder queryBuilder = QueryBuilders.wildcardQuery("empname", "*emp*");
		//QueryStringQueryBuilder queryBuilder = QueryBuilders.queryStringQuery("-26");			// full text

		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
		String json = searchSourceBuilder.query(queryBuilder).toString();
		System.out.println(json);
		return queryBuilder;
	}

	/* Refer https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-id-field.html */
	public static TermsQueryBuilder queryByIds() {
		Collection coll = new ArrayList();
		coll.add(1);
		coll.add(2);
		TermsQueryBuilder queryBuilder = QueryBuilders.termsQuery("_id", coll);
		return queryBuilder;
	}

}

3.2 手工Restful连接搜索(Java)

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;

/* Implement RestFul manually (fast)
 * Refer
 * http://stackoverflow.com/questions/33889866/how-to-send-url-request-with-json-to-elasticsearch-using-java
 * http://blog.csdn.net/dm_vincent/article/details/41693125
 * */
public class EsQuery02 {

	public static void main(String[] args) throws Exception {
		HttpURLConnection conn = null;
		DataOutputStream wr = null;
		BufferedReader br = null;
		StringBuilder resultBuilder = new StringBuilder();
		String line = null;
		try {
			// 1. Prepare url
			String url01 = "http://centos1:9200/dept/employee/_search?pretty";

			// 2. Prepare query param
			//String queryParamJson = buildQueryParamByStr();
			String queryParamJson = buildQueryParamByAPI();

			// 3. Inject url
			URL url = new URL(url01);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "application/json");
			conn.setRequestProperty("Content-Length",
					Integer.toString(queryParamJson.getBytes().length));
			conn.setRequestProperty("Content-Language", "en-US");
			conn.setUseCaches(false);
			conn.setDoOutput(true);

			// 4. Inject query param
			wr = new DataOutputStream (
					conn.getOutputStream());
			wr.writeBytes(queryParamJson);

			// Connection failure handling
			if (conn.getResponseCode() != 200) {
	            throw new RuntimeException("Failed : HTTP error code : "
	                    + conn.getResponseCode());
	        }

			// 5. Get Response
			br = new BufferedReader(new InputStreamReader(
	                (conn.getInputStream())));
			while ((line = br.readLine()) != null) {
				resultBuilder.append(line);
				resultBuilder.append(‘\r‘);
	        }
			System.out.println("result~~~" + resultBuilder.toString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(wr != null) {
				wr.close();
			}
			if(br != null) {
				br.close();
			}
			if(conn != null) {
				conn.disconnect();
			}
		}
	}

	public static String buildQueryParamByAPI() {
		MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("empname", "emp2");
		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
		String queryParamJson = searchSourceBuilder.query(queryBuilder).toString();
		System.out.println("json~~~" + queryParamJson);
		return queryParamJson;
	}
	public static String buildQueryParamByStr() {
		/*curl ‘centos1:9200/dept/employee/_search?pretty‘ -d
		 * ‘{"query" : {"match" : {"empname" : "emp2"}}}‘*/
		String queryParamJson = "{\"query\" : {\"match\" : {\"empname\" : \"emp2\"}}}";
		return queryParamJson;
	}
}

3.3 Jest Restful连接搜索(Java)

import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import io.searchbox.client.http.JestHttpClient;

/* Implement RestFul by Jest
 * Refer:
 * http://www.searchly.com/documentation/developer-api-guide/java-jest/
 * http://www.cnblogs.com/huangfox/p/3542858.html
 * http://www.169it.com/article/13172689366007246587.html
 * https://github.com/searchbox-io/Jest/tree/master/jest
 * download: https://oss.sonatype.org/content/groups/public/io/searchbox/jest/2.0.2/
 * mvn: http://www.searchly.com/documentation/developer-api-guide/java-jest/
 * */
public class EsQuery03 {
	/*
	String connUrl = "http://centos1:9200";

	public static void main(String[] args) {
		// 1. connect
		JestClient client = getClient();
		// 2. prepare query param
		String queryParamJson = buildQueryParamByAPI();
		// 3. search
		SearchResult result = search(client, queryParamJson);
		// 4. get response
		getContent();

	}

	public static JestClient getClient() {
		JestClientFactory factory = new JestClientFactory();
		factory.setHttpClientConfig(new HttpClientConfig
		       .Builder(connUrl)
		       .multiThreaded(true)
		       .build());
		JestClient client = factory.getObject();
		return client;
	}

	public static String buildQueryParamByAPI(String queryParamJson) {
		MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("empname", "emp2");
		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
		searchSourceBuilder.query(queryBuilder);
		return searchSourceBuilder.toString();
	}

	public static String buildQueryParamByStr() {
		String queryParamJson = "{\"query\" : {\"match\" : {\"empname\" : \"emp2\"}}}";
		return queryParamJson;
	}

	public static SearchResult search(JestClient client, String queryParamJson) {
		Search search = (Search) new Search.Builder(queryParamJson)
        // multiple index or types can be added.
        .addIndex("dept")
        .addType("employee")
        .build();

		//JestResult result = client.execute(search);
		SearchResult result = client.execute(search);
		return result;
	}

	public static void getContent() {
		//List<Article> articles = result.getSourceAsObjectList(Article.class);
		//List<SearchResult.Hit<Article, Void>> hits = searchResult.getHits(Article.class);
	}
	*/
}
时间: 2024-08-05 11:18:17

elasticsearch java API 实现搜索样例的相关文章

Elasticsearch java api 基本搜索部分详解

版权声明:本文非原创文章,转载出处:http://blog.csdn.net/molong1208/article/details/50512149 一.所使用版本的介绍 使用的是elasticsearch2.1.0版本,在此只是简单介绍搜索部分的api使用 二.简单的搜索 使用api的时候,基本上可以将DSL搜索的所有情况均写出来,在此给出一个最简单搜索的全部的过程以及代码,之后将对不同的搜索只是针对函数进行介绍 (1)DSL搜索 对于最简单的DSL搜索,对一个词进行搜索使用url直接进行通信

Elasticsearch Java API (二): index创建删除 cluster管理

Elasticsearch Java API (二): index创建删除 cluster管理  elastic官网有权威的java api 英文的 需要耐心看 这里整理下基本操作 创建maven工程添加依赖 <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <version>5.2.2</ver

ElasticSearch Java Api -检索索引库

上篇博客记录了如何用java调用api把数据写入索引,这次记录下如何搜索. 一.准备数据 String data1 = JsonUtil.model2Json(new Blog(1, "git简介", "2016-06-19", "SVN与Git最主要的区别...")); String data2 = JsonUtil.model2Json(new Blog(2, "Java中泛型的介绍与简单使用", "2016-0

第08章 ElasticSearch Java API

本章内容 使用客户端对象(client object)连接到本地或远程ElasticSearch集群. 逐条或批量索引文档. 更新文档内容. 使用各种ElasticSearch支持的查询方式. 处理ElasticSearch返回的错误信息. 通过发送各种管理指令来收集集群状态信息或执行管理任务. 8.3 连接到集群 8.3.1 成为ElasticSearch节点 第一种连接到ElasticSearch节点的方式是把应用程序当成ElasticSearch集群中的一个节点. Node node=no

独孤九剑之Elasticsearch Java API破剑式

0.题记之前Elasticsearch的应用比较多,但大多集中在关系型.非关系型数据库与Elasticsearch之间的同步.以上内容完成了Elasticsearch所需要的基础数据量的供给.但想要在海量的数据中找到和自己相关的业务数据,实现对已有的数据实现全文检索.分类统计等功能并应用到业务系统中,必须借助Java API来实现. 1.Elasticsearch Java API 概览Elasticsearch Java API 相关使用研究结果: 1.1 国内的博文讲解Elasticsear

ElasticSearch Java Api -创建索引

ElasticSearch JAVA API官网文档:https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs-index.html 一.生成JSON 创建索引的第一步是要把对象转换为JSON字符串.官网给出了四种创建JSON文档的方法: 1.1手写方式生成 String json = "{" + "\"user\":\"kimchy\"

Elasticsearch Java API(八)--搜索有相同父id的子文档

需求: 搜索具有相同父id的所有子文档. 数据:    mapping:      { "mappings": { "branch": {}, "employee": { "_parent": { "type": "branch" } } } } 父文档: { "index": { "_id": "london" }} { &q

Elasticsearch Java API(七)--多级嵌套搜索

要在java中实现一个有三级父子关系的嵌套搜索,相关资料很少,发在stackoverflow上以后一个Switzerland的大神很快回复了我,google+stackoverflow很好使.对应的命令行query: { "query": { "has_child": { "type": "instance", "query": { "has_child": { "type&q

百度语音识别API的使用样例(python实现)

百度给的样例程序,不论C还是Java版,都分为method1和method2两种 前者称为隐式(post的是json串,音频数据编码到json里),后者称为显式(post的就是音频数据) 一开始考虑到python wave包处理的都是"字符串",担心跟C语言的数组不一致,所以选择低效但保险的method1, 即先将音频数据base64编码,再加上采样率.通道数等信息汇集成dict,最后总体编码成json串 结果老是报: 3300 输入参数不正确 先后试过urllib2和pycurl包,