ElasticSearch之——Java操作ES实例(基于ES-2.3.0)

转载请注明出处:http://blog.csdn.net/l1028386804/article/details/78758691

今天,我们就来看看如何利用Java API来操作ES的数据,这里不讲理论的东西了,大家可以参看其他资料了解,这里直接给出实例代码。好了不多说了,我们直接上代码:

1、获取client句柄

 

/**
 * 获取client句柄
 * @return
 * @throws Exception
 */
private static Client getClient() throws Exception{
	//此处的IP是安装ES所在的主机IP地址
	return TransportClient.builder().build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.209.121"), 9300));
}

 

2、创建索引文件

 

/**
 * 创建索引文件 
 */
public static void createIndexFile() throws Exception{
	XContentBuilder mapping  = XContentFactory.jsonBuilder()
			.startObject()
				.startObject("settings")
					.field("number_of_shards", 1)
					.field("number_of_replicas", 0)
				.endObject()
			.endObject()
			.startObject()
				.startObject("type_name")
					.startObject("properties")
						.startObject("type").field("type", "string").field("store", "yes").endObject()
						.startObject("eventCount").field("type", "long").field("store", "yes").endObject()
						.startObject("eventDate").field("type","date").field("format", "dateOptionalTime").field("store", "yes").endObject()
						.startObject("message").field("type","string").field("index", "not_analyzed").field("store", "yes").endObject()
					.endObject()
				.endObject()
			.endObject();
	
	CreateIndexRequestBuilder builder = getClient().admin().indices().prepareCreate("index_name").setSource(mapping);
	
	CreateIndexResponse response = builder.execute().actionGet();
	if(response.isAcknowledged()){
		System.out.println("创建索引文档成功!");
	}else{
		System.out.println("创建索引文档失败!");
	}
}

 

3、增加索引文件

 

/**
 * 增加文档
 * @throws Exception
 */
public static void addIndexFile() throws Exception{
	IndexResponse response = getClient().prepareIndex("index_name_second", "type_name_second", "1")
			.setSource( XContentFactory.jsonBuilder().startObject()
					.field("type","liuyazhuang")
					.field("eventCount", 1)
					.field("eventDate", new Date())
					.field("message", "my name is liuyazhuang").endObject()).get();
	System.out.println("index: " + response.getIndex() + " insert doc id: " + response.getId());
}

 

4、修改索引文件

 

/**
 * 修改文档方式1
 * @throws Exception
 */
public static void updateIndexFile01() throws Exception{
	UpdateRequest updateRequest = new UpdateRequest();
	updateRequest.index("index_name_second");
	updateRequest.type("type_name_second");
	updateRequest.id("1");
	updateRequest.doc( XContentFactory.jsonBuilder().startObject().field("type", "lyz").endObject());
	System.out.println(getClient().update(updateRequest).get());
}


/**
 * 修改文档方式2
 * @throws Exception
 */
public static void updateIndexFile02() throws Exception{
	IndexRequest indexRequest = new IndexRequest("index_name_second", "type_name_second", "3")
			.source(XContentFactory.jsonBuilder()
					.startObject()
						.field("type","liuyazhuang")
						.field("eventCount", 1)
						.field("eventDate", new Date())
						.field("message", "my name is liuyazhuang")
					.endObject());
	UpdateRequest request = new UpdateRequest("index_name_second", "type_name_second", "3")
			.doc(XContentFactory.jsonBuilder().startObject().field("type", "lyz").endObject()).upsert(indexRequest);
	System.out.println(getClient().update(request).get());
}

 

5、查询文件

 

/**
 * 查询文档
 * @throws Exception
 */
public static void queryIndexFile() throws Exception{
	GetResponse response = getClient().prepareGet("index_name_second", "type_name_second", "1").get();
	String source = response.getSource().toString();
	long version = response.getVersion();
	String indexName = response.getIndex();
	String type = response.getType();
	String id = response.getId();
	
	System.out.println("source===>>> " + source + ",  version====>>> " + version + ", indexName=====>>> " + indexName + ", type====>>> " + type + ", id====>>> " + id);
}

 

6、删除文件

 

/**
 * 删除文档
 * @throws Exception
 */
public static void deleteIndexFile() throws Exception{
	DeleteResponse response = getClient().prepareDelete("index_name_second", "type_name_second", "1").get();
	System.out.println(response.isFound());  //文档存在返回true, 不存在返回false
}

 

7、删除索引

 

/**
 * 删除索引
 * @throws Exception
 */
public static void deleteIndex() throws Exception{
	DeleteIndexRequest delete = new DeleteIndexRequest("index_name_second");
	System.out.println(getClient().admin().indices().delete(delete));
}

 

8、完整的操作类

 

package com.lyz.es.test;

import java.net.InetAddress;
import java.util.Date;

import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;

/**
 * 索引文件的工具类
 * @author liuyazhuang
 *
 */
public class IndexFileUtils {
	
	
	/**
	 * 获取client句柄
	 * @return
	 * @throws Exception
	 */
	private static Client getClient() throws Exception{
		//此处的IP是安装ES所在的主机IP地址
		return TransportClient.builder().build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.209.121"), 9300));
	}
	
	/**
	 * 创建索引文件 
	 */
	public static void createIndexFile() throws Exception{
		XContentBuilder mapping  = XContentFactory.jsonBuilder()
				.startObject()
					.startObject("settings")
						.field("number_of_shards", 1)
						.field("number_of_replicas", 0)
					.endObject()
				.endObject()
				.startObject()
					.startObject("type_name")
						.startObject("properties")
							.startObject("type").field("type", "string").field("store", "yes").endObject()
							.startObject("eventCount").field("type", "long").field("store", "yes").endObject()
							.startObject("eventDate").field("type","date").field("format", "dateOptionalTime").field("store", "yes").endObject()
							.startObject("message").field("type","string").field("index", "not_analyzed").field("store", "yes").endObject()
						.endObject()
					.endObject()
				.endObject();
		
		CreateIndexRequestBuilder builder = getClient().admin().indices().prepareCreate("index_name").setSource(mapping);
		
		CreateIndexResponse response = builder.execute().actionGet();
		if(response.isAcknowledged()){
			System.out.println("创建索引文档成功!");
		}else{
			System.out.println("创建索引文档失败!");
		}
	}
	
	/**
	 * 增加文档
	 * @throws Exception
	 */
	public static void addIndexFile() throws Exception{
		IndexResponse response = getClient().prepareIndex("index_name_second", "type_name_second", "1")
				.setSource( XContentFactory.jsonBuilder().startObject()
						.field("type","liuyazhuang")
						.field("eventCount", 1)
						.field("eventDate", new Date())
						.field("message", "my name is liuyazhuang").endObject()).get();
		System.out.println("index: " + response.getIndex() + " insert doc id: " + response.getId());
	}
	
	
	/**
	 * 修改文档方式1
	 * @throws Exception
	 */
	public static void updateIndexFile01() throws Exception{
		UpdateRequest updateRequest = new UpdateRequest();
		updateRequest.index("index_name_second");
		updateRequest.type("type_name_second");
		updateRequest.id("1");
		updateRequest.doc( XContentFactory.jsonBuilder().startObject().field("type", "lyz").endObject());
		System.out.println(getClient().update(updateRequest).get());
	}
	
	
	/**
	 * 修改文档方式2
	 * @throws Exception
	 */
	public static void updateIndexFile02() throws Exception{
		IndexRequest indexRequest = new IndexRequest("index_name_second", "type_name_second", "3")
				.source(XContentFactory.jsonBuilder()
						.startObject()
							.field("type","liuyazhuang")
							.field("eventCount", 1)
							.field("eventDate", new Date())
							.field("message", "my name is liuyazhuang")
						.endObject());
		UpdateRequest request = new UpdateRequest("index_name_second", "type_name_second", "3")
				.doc(XContentFactory.jsonBuilder().startObject().field("type", "lyz").endObject()).upsert(indexRequest);
		System.out.println(getClient().update(request).get());
	}
	
	/**
	 * 查询文档
	 * @throws Exception
	 */
	public static void queryIndexFile() throws Exception{
		GetResponse response = getClient().prepareGet("index_name_second", "type_name_second", "1").get();
		String source = response.getSource().toString();
		long version = response.getVersion();
		String indexName = response.getIndex();
		String type = response.getType();
		String id = response.getId();
		
		System.out.println("source===>>> " + source + ",  version====>>> " + version + ", indexName=====>>> " + indexName + ", type====>>> " + type + ", id====>>> " + id);
	}
	
	
	/**
	 * 删除文档
	 * @throws Exception
	 */
	public static void deleteIndexFile() throws Exception{
		DeleteResponse response = getClient().prepareDelete("index_name_second", "type_name_second", "1").get();
		System.out.println(response.isFound());  //文档存在返回true, 不存在返回false
	}
	
	
	/**
	 * 删除索引
	 * @throws Exception
	 */
	public static void deleteIndex() throws Exception{
		DeleteIndexRequest delete = new DeleteIndexRequest("index_name_second");
		System.out.println(getClient().admin().indices().delete(delete));
	}
}

 

9、测试类

 

package com.lyz.es.test;

import org.junit.Test;

/**
 * 测试es
 * @author liuyazhuang
 *
 */
public class IndexFileTest {
	
	@Test
	public void testCreateIndexFile() throws Exception{
		IndexFileUtils.createIndexFile();
	}
	
	@Test
	public void testAddIndexFile() throws Exception{
		IndexFileUtils.addIndexFile();
	}
	
	@Test
	public void testUpdateIndexFile01() throws Exception{
		IndexFileUtils.updateIndexFile01();
	}
	
	@Test
	public void testQueryIndexFile() throws Exception{
		IndexFileUtils.queryIndexFile();
	}
	
	@Test
	public void testDeleteIndexFile() throws Exception{
		IndexFileUtils.deleteIndexFile();
	}
	
	@Test
	public void testDeleteIndex() throws Exception{
		IndexFileUtils.deleteIndex();
	}
}

 

10、pom.xml

 



  4.0.0
  com.lyz
  es
  1.0.0-SNAPSHOT
  jar
	   
	
   		
   			org.elasticsearch
   			elasticsearch
   			2.3.0
   		
   
   
  
		es
		
			
				${project.build.directory}/classes
				src/main/resources
				true
				
					**/*.xml
					**/*.properties
				
			
			
			
				${project.build.directory}/classes/META-INF/spring
				src/main/resources/spring
				true
				
					spring-context.xml
				
			
		
		
		
			
				
				
					org.eclipse.m2e
					lifecycle-mapping
					1.0.0
					
						
							
								
									
										org.apache.maven.plugins
										maven-dependency-plugin
										  [2.0,)  
										
											copy-dependencies
										
									
									
										
									
								
							
						
					
				
			
		
		
			
			
				org.apache.maven.plugins
				maven-jar-plugin
				
					target/classes/
					
						
							com.alibaba.dubbo.container.Main
							
							false
							true
							lib/
						
						
							.
						
					
				
			
			
				org.apache.maven.plugins
				maven-dependency-plugin
				
					
						copy-dependencies
						package
						
							copy-dependencies
						
						
							jar
							jar
							false
							
								${project.build.directory}/lib
							
						
					
				
			
		


11、温馨提示

大家可以到链接http://download.csdn.net/download/l1028386804/10152051下载Java API操作ElasticSearch的完整实例。

 

 

 

你可能感兴趣的:(ElasticSearch,搜索优化)