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

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.lyz</groupId>
  <artifactId>es</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>jar</packaging>
	   
	<dependencies>
   		<dependency>
   			<groupId>org.elasticsearch</groupId>
   			<artifactId>elasticsearch</artifactId>
   			<version>2.3.0</version>
   		</dependency>
   </dependencies>
   
  <build>
		<finalName>es</finalName>
		<resources>
			<resource>
				<targetPath>${project.build.directory}/classes</targetPath>
				<directory>src/main/resources</directory>
				<filtering>true</filtering>
				<includes>
					<include>**/*.xml</include>
					<include>**/*.properties</include>
				</includes>
			</resource>
			<!-- 结合com.alibaba.dubbo.container.Main -->
			<resource>
				<targetPath>${project.build.directory}/classes/META-INF/spring</targetPath>
				<directory>src/main/resources/spring</directory>
				<filtering>true</filtering>
				<includes>
					<include>spring-context.xml</include>
				</includes>
			</resource>
		</resources>
		
		<pluginManagement>
			<plugins>
				<!-- 解决Maven插件在Eclipse内执行了一系列的生命周期引起冲突 -->
				<plugin>
					<groupId>org.eclipse.m2e</groupId>
					<artifactId>lifecycle-mapping</artifactId>
					<version>1.0.0</version>
					<configuration>
						<lifecycleMappingMetadata>
							<pluginExecutions>
								<pluginExecution>
									<pluginExecutionFilter>
										<groupId>org.apache.maven.plugins</groupId>
										<artifactId>maven-dependency-plugin</artifactId>
										  <versionRange>[2.0,)</versionRange>  
										<goals>
											<goal>copy-dependencies</goal>
										</goals>
									</pluginExecutionFilter>
									<action>
										<ignore />
									</action>
								</pluginExecution>
							</pluginExecutions>
						</lifecycleMappingMetadata>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
		<plugins>
			<!-- 打包jar文件时,配置manifest文件,加入lib包的jar依赖 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>
					<classesDirectory>target/classes/</classesDirectory>
					<archive>
						<manifest>
							<mainClass>com.alibaba.dubbo.container.Main</mainClass>
							<!-- 打包时 MANIFEST.MF文件不记录的时间戳版本 -->
							<useUniqueVersions>false</useUniqueVersions>
							<addClasspath>true</addClasspath>
							<classpathPrefix>lib/</classpathPrefix>
						</manifest>
						<manifestEntries>
							<Class-Path>.</Class-Path>
						</manifestEntries>
					</archive>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
				<executions>
					<execution>
						<id>copy-dependencies</id>
						<phase>package</phase>
						<goals>
							<goal>copy-dependencies</goal>
						</goals>
						<configuration>
							<type>jar</type>
							<includeTypes>jar</includeTypes>
							<useUniqueVersions>false</useUniqueVersions>
							<outputDirectory>
								${project.build.directory}/lib
							</outputDirectory>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>

</build>
</project>

11、温馨提示

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

 

 

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冰 河

可以吃鸡腿么?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值