欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

elasticsearch 学习笔记(2)-客户端编程【原创】

程序员文章站 2022-04-03 14:49:28
...
客户端编程可以自己封装json http请求,也可以采用es客户端API。这里介绍API方式。
1. 初始化Client
public void init() {
		String clusterName="elasticsearch";
		String ip= "192.168.180.15";
		Settings settings = Settings.settingsBuilder()
		        .put("cluster.name", clusterName)
		        .build();
		try {
		    client = TransportClient.builder()
		            .settings(settings).build()
		            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(ip),9300));
		    createMapping("index", "type");		} catch (Exception e) {
		   	e.printStackTrace();
		}
	}

分词映射:
private void createMapping(String indices,String mappingType)throws Exception{
	new XContentFactory();
		XContentBuilder builder=XContentFactory.jsonBuilder()
		.startObject()
			.startObject(mappingType)
				.startObject("properties")
					.startObject("XXX").field("type", "string").field("store", "yes").field("index","not_analyzed").endObject()
					.startObject("YYY").field("type", "string").field("store", "yes").field("analyzer", "ik").endObject()
					.startObject("ZZZ").field("type", "double").field("store", "yes").field("index","not_analyzed").endObject()				.endObject()
			.endObject()
		.endObject();
		PutMappingRequest mapping = Requests.putMappingRequest(indices).type(mappingType).source(builder);
		client.admin().indices().putMapping(mapping).actionGet();
	}

XXX,YYY,ZZZ代表业务字段,因为只演示技术,所以以虚拟字段代替。

2. 创建索引
//其中的map为业务数据,key=XXX/YYY/ZZZ
private void createChineseIndex(String id, Map<String, Object> map) throws Exception{
		client.prepareIndex("index", "type", id).setSource(generateJson(map))
		.execute().actionGet();
	}
//生成json请求数据
private String generateJson(Map<String, Object> map) {
		String json = "";
		try {
			XContentBuilder contentBuilder = XContentFactory.jsonBuilder()
					.startObject();
			for(String key:map.keySet()){
				contentBuilder.field(key, map.get(key));
			}
			json = contentBuilder.endObject().string();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return json;
	}


3. 分组统计
private String searchGoodsName(String goodsName) {
		String fullGoodsName=null;
		SearchResponse response = client.prepareSearch("index")
				.setTypes("type")
				.setSearchType(SearchType.COUNT)
				.setQuery(QueryBuilders.termQuery("XXX", goodsName))
				.addAggregation(AggregationBuilders.terms("gCount").field("YYY"))
				.execute().actionGet();
		StringTerms gNameTerms = (StringTerms) response.getAggregations().get("gCount");
		
		Iterator<Bucket> gradeBucketIt = gNameTerms.getBuckets().iterator();
		
		while(gradeBucketIt.hasNext())
		{
			Bucket gradeBucket = gradeBucketIt.next();
			System.out.println("名称:"+gradeBucket.getKey() + ",数量" + gradeBucket.getDocCount());
			if(fullGoodsName==null){
				fullGoodsName=gradeBucket.getKey().toString();
			}
		}
		
		return fullGoodsName;
	}

4.排序
SearchResponse response = client.prepareSearch("index")
				.setTypes("type")
				.setSearchType(SearchType.DFS_QUERY_AND_FETCH)
				.setQuery(QueryBuilders.termQuery("XXX", name)) // Query
				.setPostFilter(QueryBuilders.termQuery("YYY", value))
				.addSort("ZZZ", SortOrder.ASC)                       // Filter
				.setFrom(0).setSize(60).execute().actionGet();

5.简单查询
SearchResponse response = client.prepareSearch("index")
				.setTypes("type")
				.setSearchType(SearchType.DFS_QUERY_AND_FETCH)
				.setQuery(QueryBuilders.termQuery("XXX", name)) // Query
				.setPostFilter(QueryBuilders.termQuery("YYY", value))
				.setFrom(0).setSize(60).setExplain(false).execute().actionGet();

6.关闭客户端
public void close() {
		client.close();
	}