1.创建一个Maven工程,在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>elasticsearch-demo</groupId>
<artifactId>elasticsearch-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>elasticsearch-demo</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- 日志依赖 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.5.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-1.2-api</artifactId>
<version>2.8.2</version>
</dependency>
</dependencies>
</project>
2. 通过Java程序连接Elasticsearch
需要注意的是,上一章节我们通过浏览器http://127.0.0.1:9200访问可以正常访问,这里需要知晓,9200端口是用于Http协议访问的,如果通过客户端访问需要通过9300端口才可以访问
package com;import java.net.InetAddress;
import java.net.UnknownHostException;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ElasticsearchTest1
{
private Logger logger = LoggerFactory.getLogger(ElasticsearchTest1.class);
public final static String HOST = "127.0.0.1";
public final static int PORT = 9300;// http请求的端口是9200,客户端是9300
@SuppressWarnings("resource")
@Test
public void test1() throws UnknownHostException
{
// 创建客户端
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddresses(new InetSocketTransportAddress(InetAddress.getByName(HOST), PORT));
logger.debug("Elasticsearch connect info:" + client.toString());
// 关闭客户端
client.close();
}
}
4.log4j.properties文件创建
### set log levels ###
log4j.rootLogger = DEBUG,Console,File
### 输出到控制台 ###
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern= %d{ABSOLUTE} %5p %c{1}:%L - %m%n
### 输出到日志文件 ###
log4j.appender.File=org.apache.log4j.RollingFileAppender
log4j.appender.File.File=${project}/WEB-INF/logs/app.log
log4j.appender.File.DatePattern=_yyyyMMdd'.log'
log4j.appender.File.MaxFileSize=10MB
log4j.appender.File.Threshold=ALL
log4j.appender.File.layout=org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n
4. Elasticsearch索引库的创建
private Logger logger = LoggerFactory.getLogger(ElasticsearchTest2.class);public final static String HOST = "127.0.0.1";
public final static int PORT = 9300; // http请求的端口是9200,客户端是9300
private TransportClient client = null;
@SuppressWarnings(
{
"resource", "unchecked"
})
@Before
public void getConnect() throws UnknownHostException
{
client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddresses(new InetSocketTransportAddress(InetAddress.getByName(HOST), PORT));
logger.info("连接信息:" + client.toString());
}
@After
public void closeConnect()
{
if (null != client)
{
logger.info("执行关闭连接操作...");
client.close();
}
}
@Test
public void addIndex1() throws IOException
{
IndexResponse response = client.prepareIndex("msg", "tweet", "1").setSource(XContentFactory.jsonBuilder()
.startObject().field("userName", "张三").field("sendDate", new Date()).field("msg", "你好李四").endObject())
.get();
logger.info("索引名称:" + response.getIndex() + "\n类型:" + response.getType() + "\n文档ID:" + response.getId()
+ "\n当前实例状态:");
}
5.测试
测试Elasticsearch客户端连接
测试创建的索引库是否成功