首页 > 其他分享 >Elasticsearch_API操作

Elasticsearch_API操作

时间:2022-11-11 16:38:55浏览次数:55  
标签:index indexResponse System API Elasticsearch client println 操作 out


 Elasticsearch的Java客户端非常强大;它可以建立一个嵌入式实例并在必要时运行管理任务。运行一个Java应用程序和Elasticsearch时,有两种操作模式可供使用。该应用程序可在Elasticsearch集群中扮演更加主动或更加被动的角色。在更加主动的情况下(称为Node Client),应用程序实例将从集群接收请求,确定哪个节点应处理该请求,就像正常节点所做的一样。(应用程序甚至可以托管索引和处理请求。)另一种模式称为Transport Client,它将所有请求都转发到另一个Elasticsearch节点,由后者来确定最终目标

1 API基本操作

1.1 操作环境准备

1)创建maven工程

Elasticsearch_API操作_搜索

2)添加pom文件

<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>
</dependencies>

3)等待依赖的jar包下载完成

Elasticsearch_API操作_json_02

当直接在ElasticSearch 建立文档对象时,如果索引不存在的,默认会自动创建,映射采用默认方式

1.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("hadoop102"), 9300));

// 3 打印集群名称
System.out.println(client.toString());
}

1.3 创建索引

1)源代码

@Test
publicvoid createIndex_blog(){
// 1 创建索引
client.admin().indices().prepareCreate("blog2").get();

// 2 关闭连接
client.close();
}

2)查看结果

{"blog2":{"aliases":{},"mappings":{},"settings":{"index":{"creation_date":"1507466730030","number_of_shards":"5","number_of_replicas":"1","uuid":"lec0xYiBSmStspGVa6c80Q","version":{"created":"5060299"},"provided_name":"blog2"}}}}

1.4 删除索引

1)源代码

@Test
publicvoid deleteIndex(){
// 1 删除索引
client.admin().indices().prepareDelete("blog2").get();

// 2 关闭连接
client.close();
}

2)查看结果

浏览器查看http://hadoop102:9200/blog2

没有blog2索引了。

{"error":{"root_cause":[{"type":"index_not_found_exception","reason":"no such index","resource.type":"index_or_alias","resource.id":"blog2","index_uuid":"_na_","index":"blog2"}],"type":"index_not_found_exception","reason":"no such index","resource.type":"index_or_alias","resource.id":"blog2","index_uuid":"_na_","index":"blog2"},"status":404}

1.5 新建文档(源数据json串)

当直接在ElasticSearch建立文档对象时,如果索引不存在的,默认会自动创建,映射采用默认方式。

ElasticSearch服务默认端口9300

Web管理平台端口9200

1)源代码

@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();
}

 

 

1.6 新建文档(源数据map方式添加json)

1)源代码

@Test

       publicvoid createIndexByMap() {

 

              // 1 文档数据准备

              Map<String, Object> json = new HashMap<String, Object>();

              json.put("id", "2");

              json.put("title", "基于Lucene的搜索服务器");

              json.put("content", "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口");

 

              // 2 创建文档

              IndexResponse indexResponse = client.prepareIndex("blog", "article", "2").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();

       }

1.7 新建文档(源数据es构建器添加json)

1)源代码

@Test
public void createIndex() throws Exception {

// 1 通过es自带的帮助类,构建json数据
XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("id", 3)
.field("title", "基于Lucene的搜索服务器").field("content", "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。")
.endObject();

// 2 创建文档
IndexResponse indexResponse = client.prepareIndex("blog", "article", "3").setSource(builder).get();

// 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();
}

 

1.8 搜索文档数据(单个索引)

1)源代码

@Test
publicvoid getData() throws Exception {

// 1 查询文档
GetResponse response = client.prepareGet("blog", "article", "1").get();

// 2 打印搜索的结果
System.out.println(response.getSourceAsString());

// 3 关闭连接
client.close();
}

 

1.9 搜索文档数据(多个索引)

1)源代码

@Test
publicvoid getMultiData() {

// 1 查询多个文档
MultiGetResponse response = client.prepareMultiGet().add("blog", "article", "1").add("blog", "article", "2", "3")
.add("blog", "article", "2").get();

// 2 遍历返回的结果
for(MultiGetItemResponse itemResponse:response){
GetResponse getResponse = itemResponse.getResponse();

// 如果获取到查询结果
if (getResponse.isExists()) {
String sourceAsString = getResponse.getSourceAsString();
System.out.println(sourceAsString);
}
}

// 3 关闭资源
client.close();
}

2)结果查看

{"id":"1","title":"基于Lucene的搜索服务器","content":"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口"}

{"content":"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口","id":"2","title":"基于Lucene的搜索服务器"}

{"id":3,"titile":"ElasticSearch是一个基于Lucene的搜索服务器","content":"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。"}

{"content":"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口","id":"2","title":"基于Lucene的搜索服务器"}

1.10 更新文档数据(update)

1)源代码

@Test
publicvoid updateData() throws Throwable {

// 1 创建更新数据的请求对象
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index("blog");
updateRequest.type("article");
updateRequest.id("3");

updateRequest.doc(XContentFactory.jsonBuilder().startObject()
// 对没有的字段添加, 对已有的字段替换
.field("title", "基于Lucene的搜索服务器")
.field("content",
大数据前景无限")
.field("createDate", "2017-8-22").endObject());

// 2 获取更新后的值
UpdateResponse indexResponse = client.update(updateRequest).get();

// 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("create:" + indexResponse.getResult());

// 4 关闭连接
client.close();
}

 

1.11 更新文档数据(upsert)

设置查询条件, 查找不到则添加IndexRequest内容,查找到则按照UpdateRequest更新。

@Test
publicvoid testUpsert() throws Exception {

// 设置查询条件, 查找不到则添加
IndexRequest indexRequest = new IndexRequest("blog", "article", "5")
.source(XContentFactory.jsonBuilder().startObject().field("title", "搜索服务器").field("content","它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。").endObject());

// 设置更新, 查找到更新下面的设置
UpdateRequest upsert = new UpdateRequest("blog", "article", "5")
.doc(XContentFactory.jsonBuilder().startObject().field("user", "李四").endObject()).upsert(indexRequest);

client.update(upsert).get();
client.close();
}

第一次执行

hadoop102:9200/blog/article/5

Elasticsearch_API操作_json_03

 

第二次执行

hadoop102:9200/blog/article/5

Elasticsearch_API操作_搜索_04

 

 

1.12 删除文档数据(prepareDelete)

1)源代码

@Test
publicvoid deleteData() {

// 1 删除文档数据
DeleteResponse indexResponse = client.prepareDelete("blog", "article", "5").get();

// 2 打印返回的结果
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("found:" + indexResponse.getResult());

// 3 关闭连接
client.close();
}

标签:index,indexResponse,System,API,Elasticsearch,client,println,操作,out
From: https://blog.51cto.com/u_12654321/5845128

相关文章

  • etcd member操作
    查看集群中存在的节点$etcdctlmemberlist8e9e05c52164694d:name=dev-master-01peerURLs=http://localhost:2380clientURLs=http://localhost:2379isLeader=true删......
  • 微服务网关 APISIX 群集配置指南
    1.前言APISIX通过ETCD存储数据,利用ETCD本身的功能实现群集管理和控制。有关APISIX的安装配置详情参考“​​APISIX网关CentOS7环境安装配置​​”。前面文章描述......
  • [Typescript] 97. Hard - Capitalize Words
    Implement CapitalizeWords<T> whichconvertsthefirstletterof eachwordofastring touppercaseandleavestherestas-is.Forexampletypecapitalized......
  • 【JSR269实战】之编译时操作AST,修改字节码文件,以实现和lombok类似的功能
    参考:https://blog.csdn.net/justry_deng/article/details/106176181maven编译不成功。笔者日常****:兄弟姐妹们,还是尽量少熬夜啊。我感觉我记性有所下降,难受。需求说......
  • GCC-1——内嵌原子操作
    一、GCC内嵌原子操作翻译5.44用于原子内存访问的内置函数以下内置函数旨在与英特尔安腾处理器特定应用程序二进制接口第7.4节中描述的函数兼容。因此,它们偏离了使用......
  • ElasticSearch7.0实例精讲之第一章入门
    目录1、技术要求2、下载并安装Elasticserch3、设置网络4、设置节点5、设置linux系统6、设置不同的节点系统7、设置协调器节点8、设置采集节点9、在elasticsearch安装插件10......
  • API 中签名的使用
    ​   今天一同事沟通接口服务签名问题,特整理了一下,便于他人查阅。 一、为什么要签名?  接口服务需要解决的三个问题请求是否合法:是否是我的信任方......
  • 操作系统速成——5.设备管理
    五.设备管理5.1设备管理的目标使用方便、效率高、管理同意、与设备无关  5.2IO设备分类存储设备或输入输出设备块设备或字符设备低速中速高速设备 IO控制方式......
  • 实验7:基于REST API的SDN北向应用实践
    实验7:基于RESTAPI的SDN北向应用实践一、实验目的1.能够编写程序调用OpenDaylightRESTAPI实现特定网络功能;2.能够编写程序调用RyuRESTAPI实现特定网络功能。二、实......
  • java通过cglib动态生成实体bean的操作
    转载自:https://www.jb51.net/article/205882.htm maven依赖:12345678910<dependency>      <groupId>commons-beanutils</groupId>   ......