elasticsearch5.3集群 java 调用实例

前提先搭好集群

maven项目 pom.xml引入


			
				org.elasticsearch
				elasticsearch
				5.3.0
			
		

代码示例

package com.test.ela;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

/**
 * @author huangjiangnan
 * @email [email protected]
 * @version 1.0
 * @since 2017年4月11日 下午4:45:49 类说明
 */
public class ElaFactory {
    
	 
	private static TransportClient client;
	
	@SuppressWarnings("resource")
	public static TransportClient getClient() {
		if(client!=null){
			return client;
		}
		try {
			Settings settings = Settings.builder().put("cluster.name", "my-application")
					.put("client.transport.sniff", true).build();
			client = new PreBuiltTransportClient(settings)
					.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.7.204"), 9302))
					.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.7.204"), 9303));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return client;


	}

	public static void main(String[] args) {
		for(int i=0;i<100;i++){
			index();
			search();
		}
	}

	
	public static void search(){
		TransportClient client=getClient();
			SearchResponse response = client.prepareSearch("users")
					/*		.setTypes("user")
					        .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
					        .setQuery(QueryBuilders.termQuery("multi", "test"))                 
					        .setPostFilter(QueryBuilders.rangeQuery("age").from(0).to(18))  */  
					        .setFrom(0).setSize(60).setExplain(true)
					        .get();
					System.out.println(response);
		
	}
	
	public static void index(){
		TransportClient client = ElaFactory.getClient();
		Map map = new HashMap();
		Random ran = new Random();
		map.put("nickname", "测试" + ran.nextInt(100));
		map.put("sex", ran.nextInt(100));
		map.put("age", ran.nextInt(100));
		map.put("mobile", "15014243232");
		IndexResponse response = client.prepareIndex("users", "user").setSource(map).get();
		System.out.println(response);
	}
}

结果

elasticsearch5.3集群 java 调用实例_第1张图片


你可能感兴趣的:(全文检索)