前言
在前面的两篇文章中分别介绍了Elasticsearch和head插件的安装部署:
Elasticsearch5.2.2 安装部署与常见启动报错解决
Elasticsearch head插件安装过程详解
在本篇文章,将结合具体的例子重点介绍Elasticsearch Java API的操作。
Elasticsearch的Java客户端非常强大;它可以建立一个嵌入式实例并在必要时运行管理任务。运行一个Java应用程序和Elasticsearch时,有两种操作模式可供使用。该应用程序可在Elasticsearch集群中扮演更加主动或更加被动的角色。在更加主动的情况下(称为Node Client),应用程序实例将从集群接收请求,确定哪个节点应处理该请求,就像正常节点所做的一样。(应用程序甚至可以托管索引和处理请求。)另一种模式称为Transport Client,它将所有请求都转发到另一个Elasticsearch节点,由后者来确定最终目标。
一、API基本操作
1、操作环境准备
- Elasticsearch和head插件已经安装部署好,并已经启动成功
- 创建Maven工程,导入以下依赖:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.2.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
- 等待依赖的jar包下载完成
- 在Maven工程的resources目录下新建一个文件log4j2.xml ,然后在该文件中下入以下配置信息:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
</Console>
<RollingFile name="RollingFile" fileName="logs/strutslog1.log"
filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
<PatternLayout>
<Pattern>%d{
MM-dd-yyyy} %p %c{
1.} [%t] -%M-%L- %m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="1 KB"/>
</Policies>
<DefaultRolloverStrategy fileIndex="max" max="2"/>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="com.opensymphony.xwork2" level="WAN"/>
<Logger name="org.apache.struts2" level="WAN"/>
<Root level="warn">
<AppenderRef ref="STDOUT"/>
</Root>
</Loggers>
</Configuration>
2、获取Transport Client
(1)ElasticSearch服务默认端口9300。
(2)Web管理平台端口9200。
private TransportClient client;
@SuppressWarnings("unchecked")
@Before
public void getClient() throws Exception {
// 1 设置连接的集群名称
Settings settings = Settings.builder().put("cluster.name", "my-application").build();
// 2 连接集群
client = new PreBuiltTransportClient(settings);
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("weekend110"), 9300));
// 3 打印集群名称
System.out.println(client.toString());
}
3、创建索引
1)源代码:
/**
* 创建索引
*/
@Test
public void createIndex_blog(){
// 1 创建索引
client.admin().indices().prepareCreate("blog1").get();
// 2 关闭连接
client.close();
}
2)查看结果: http://192.168.2.100:9200/blog1
{“blog1”:{“aliases”:{},“mappings”:{},“settings”:{“index”:{“creation_date”:“1594951875136”,“number_of_shards”:“5”,“number_of_replicas”:“1”,“uuid”:“MIoleYUIRf2pBhgycwdUcQ”,“version”:{“created”:“5020299”},“provided_name”:“blog1”}}}}
4、删除索引
1)源代码:
/**
* 删除索引
*/
@Test
public void deleteIndex(){
// 1 删除索引
client.admin().indices().prepareDelete("blog1").get();
// 2 关闭连接
client.close();
}
2)查看结果: http://192.168.2.100:9200/blog1
没有blog1索引了。
{“error”:{“root_cause”:[{“type”:“index_not_found_exception”,“reason”:“no such index”,“resource.type”:“index_or_alias”,“resource.id”:“blog1”,“index_uuid”:“na”,“index”:“blog1”}],“type”:“index_not_found_exception”,“reason”:“no such index”,“resource.type”:“index_or_alias”,“resource.id”:“blog1”,“index_uuid”:“na”,“index”:“blog1”},“status”:404}
5、新建文档(源数据json串)
当直接在ElasticSearch建立文档对象时,如果索引不存在的,默认会自动创建,映射采用默认方式。
ElasticSearch服务默认端口9300
Web管理平台端口9200
1)源代码:
/**
* 源数据为 json串
* @throws UnknownHostException
*/
@Test
public void createIndexByJson() throws UnknownHostException {
// 1 文档数据准备
String json = "{" + "\"id\":\"1\"," + "\"title\":\"基于Lucene的搜索服务器\","
+ "\"content\":\"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口\"" + "}";
// 2 创建文档
IndexResponse indexResponse = client.prepareIndex("blog", "article", "1").setSource(json).execute().actionGet();
// 3 打印返回的结果
System.out.println("index:" + indexResponse.getIndex());
System.out.println("type:" + indexResponse.getType());
System.out.println("id:" + indexResponse.getId());
System.out.println("version:" + indexResponse.getVersion());
System.out.println("result:" + indexResponse.getResult());
// 4 关闭连接
client.close();
}
2)查看结果:
6、新建文档(源数据map方式添加json)
1)源代码:
/**
* 源数据 Map方式添加json
*/
@Test
public void createIndexByMap() {
// 1 文档数据准备
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", "2");
map.put("title", "基于Lucene的搜索服务器");
map.put("content", "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口");
// 2 创建文档
IndexResponse indexResponse = client.prepareIndex("blog", "article", "2").setSource(map).execute().actionGet();
// 3 打印返回的结果
System.out.println("index:" + indexResponse.getIndex());
System.out.println("type:" + indexResponse.getType());
System.out.println("id:" + indexResponse.getId());
System.out.println("version:" + indexResponse.getVersion());
System.out.println("result:" + indexResponse.getResult());
// 4 关闭连接
client.close();
}
2)查看结果: