一、ES使用,以及客户端

1、pom引用

<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.4.3</version>
</dependency>

如果测试@Test还需增加一下

        <dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>transport-netty4-client</artifactId>
<version>5.4.3</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.4.3</version>
</dependency>

2、日志添加

同时需要添加日志包引用log4j

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>

或者使用slf4j

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.24</version>
</dependency>

github地址:URL

二、index索引操作

常用查看

查看集群健康:http://127.0.0.1:9200/_cat/health?v

查看集群节点:http://127.0.0.1:9200/_cat/nodes?v

查看索引信息:http://127.0.0.1:9200/_cat/indices?v

  Elasticsearch提供了一个完整的Java API来处理管理任务。要访问它们,您需要从客户端调用admin()方法以获取AdminClient:

AdminClient adminClient = client.admin();

2.1、java API 索引的创建

方式一、自动创建索引

  需要在elasticsearch中创建自动索引,配置yml

action.auto_create_index: .security,.monitoring*,.watches,.triggered_watches,.watcher-history*,app-a-*,app-b-*

方式二、手工创建索引及基本操作

索引:要访问索引Java API,您需要从AdminClient调用indices()方法:

IndicesAdminClient indicesAdminClient = client.admin().indices();

基础帮助类【客户端、增加索引、删除索引、是否存在索引】

文档地址:https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.4/java-docs.html

索引API允许将类型化的JSON文档索引到特定索引中并使其可搜索。

查看github文档中的索引映射操作

使用header工具查看索引:http://localhost:9200/twitter_index/_mapping/tweet_type

2.2、生成json操作

  es操作多半使用nosql操作,即一般使用json格式字符串。

注意:在内部,每种类型都转换为byte [](因此String转换为byte [])。因此,如果对象已经是这种形式,那么使用它。 jsonBuilder是高度优化的JSON生成器,可直接构造byte []。

方式一、自己写一个json String或者json byte[]

String json = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"2013-01-30\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";

  注意:如果有日期类型,需要进行定义格式

方式二、使用能转化成json的map

Map<String, Object> json = new HashMap<String, Object>();
json.put("user","kimchy");
json.put("postDate",new Date());
json.put("message","trying out Elasticsearch");

方式三、使用序列化类库Jackson等

import com.fasterxml.jackson.databind.*;

// instance a json mapper
ObjectMapper mapper = new ObjectMapper(); // create once, reuse // generate json
byte[] json = mapper.writeValueAsBytes(yourbeaninstance);

方式四、使用内置帮助器XContentFactory.jsonBuilder()

import static org.elasticsearch.common.xcontent.XContentFactory.*;

XContentBuilder builder = jsonBuilder()
.startObject()
.field("user", "kimchy")
.field("postDate", new Date())
.field("message", "trying out Elasticsearch")
.endObject()

查看内容

String json = builder.string();

请注意,您还可以使用startArray(String)和endArray()方法添加数组。顺便说一下,field方法接受许多对象类型。您可以直接传递数字,日期甚至其他XContentBuilder对象。

2.3、操作线程

  索引API允许设置线程模型,当在同一节点上执行API的实际执行时将执行操作(API在同一服务器上分配的分片上执行)。

  选项是在不同的线程上执行操作,或者在调用线程上执行它(注意API仍然是异步的)。默认情况下,operationThreaded设置为true,这意味着操作在不同的线程上执行。

更多消息可以参看

三、文档操作

1)Document内容新增

方式一、对应上文方式四

import static org.elasticsearch.common.xcontent.XContentFactory.*;

IndexResponse response = client.prepareIndex("twitter", "tweet", "1")
.setSource(jsonBuilder()
.startObject()
.field("user", "kimchy")
.field("postDate", new Date())
.field("message", "trying out Elasticsearch")
.endObject()
)
.get();

方式二、序列化成String

String json = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"2013-01-30\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}"; IndexResponse response = client.prepareIndex("twitter", "tweet")
.setSource(json)
.get();

IndexResponse对象会有一个响应报告

// 索引名
String _index = response.getIndex();
// 类型名
String _type = response.getType();
// 文档ID 主键ID
String _id = response.getId();
// Version (if it's the first time you index this document, you will get: 1)
long _version = response.getVersion();
// status has stored current instance statement.
RestStatus status = response.status();

  单条记录,批量插入等请参看

4)通过ID查询记录

GetResponse response = client.prepareGet("indexName", "type", "id").get();

默认情况下,operationThreaded设置为true,这意味着操作在不同的线程上执行。这是一个将其设置为false的示例:

GetResponse response = client.prepareGet("twitter", "tweet", "1")
.setOperationThreaded(false)
.get();

5)通过ID删除文档数据

DeleteResponse response = client.prepareDelete("twitter", "tweet", "1").get();

默认情况下,operationThreaded设置为true,这意味着操作在不同的线程上执行。这是一个将其设置为false的示例:

DeleteResponse response = client.prepareDelete("twitter", "tweet", "1")
.setOperationThreaded(false)
.get();

6)根据条件删除记录

BulkByScrollResponse response =
DeleteByQueryAction.INSTANCE.newRequestBuilder(client)
.filter(QueryBuilders.matchQuery("gender", "male")) //query
.source("persons") //index
.get(); // excute long deleted = response.getDeleted(); // number

因为它可以是一个长时间运行的操作,如果你想异步地执行它,你可以调用execute而不是get并提供一个监听器,如:

DeleteByQueryAction.INSTANCE.newRequestBuilder(client)
.filter(QueryBuilders.matchQuery("gender", "male"))
.source("persons")
.execute(new ActionListener<BulkIndexByScrollResponse>() { //listener
@Override
public void onResponse(BulkIndexByScrollResponse response) {
long deleted = response.getDeleted();
}
@Override
public void onFailure(Exception e) {
// Handle the exception
}
});

7)通过ID更新

方式一、通过UpdateRequest

UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index("index");
updateRequest.type("type");
updateRequest.id("1");
updateRequest.doc(jsonBuilder()
.startObject()
.field("gender", "male")
.endObject());
client.update(updateRequest).get();

方式二、prepareUpdate方法

脚本方式

client.prepareUpdate("ttl", "doc", "1")
.setScript(new Script("ctx._source.gender = \"male\"" , ScriptService.ScriptType.INLINE, null, null))
.get();

关于脚本:它也可以是本地存储的脚本名称。在这种情况下,您需要使用ScriptService.ScriptType.FILE

doc方式

client.prepareUpdate("ttl", "doc", "1")
.setDoc(jsonBuilder()
.startObject()
.field("gender", "male")
.endObject())
.get();

更新API还支持传递部分文档,该部分文档将合并到现有文档中(简单的递归合并,对象的内部合并,替换核心“键/值”和数组)。例如:

选用其中一种即可,无法同时提供脚本和doc。

8)upsert 更新插入

对upsert的支持。如果文档不存在,则upsert元素的内容将用于索引新文档:

IndexRequest indexRequest = new IndexRequest("index", "type", "1")
.source(jsonBuilder()
.startObject()
.field("name", "Joe Smith")
.field("gender", "male")
.endObject());
UpdateRequest updateRequest = new UpdateRequest("index", "type", "1")
.doc(jsonBuilder()
.startObject()
.field("gender", "male")
.endObject())
.upsert(indexRequest);
client.update(updateRequest).get();

如果文档不存在,将添加indexRequest中的文档

9)多ID获取

MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
.add("twitter", "tweet", "1")
.add("twitter", "tweet", "2", "3", "4")
.add("another", "type", "foo")
.get(); for (MultiGetItemResponse itemResponse : multiGetItemResponses) {
GetResponse response = itemResponse.getResponse();
if (response.isExists()) {
String json = response.getSourceAsString();
}
}

10)批量插入API

import static org.elasticsearch.common.xcontent.XContentFactory.*;

BulkRequestBuilder bulkRequest = client.prepareBulk();

// either use client#prepare, or use Requests# to directly build index/delete requests
bulkRequest.add(client.prepareIndex("twitter", "tweet", "1")
.setSource(jsonBuilder()
.startObject()
.field("user", "kimchy")
.field("postDate", new Date())
.field("message", "trying out Elasticsearch")
.endObject()
)
); bulkRequest.add(client.prepareIndex("twitter", "tweet", "2")
.setSource(jsonBuilder()
.startObject()
.field("user", "kimchy")
.field("postDate", new Date())
.field("message", "another post")
.endObject()
)
); BulkResponse bulkResponse = bulkRequest.get();
if (bulkResponse.hasFailures()) {
// process failures by iterating through each bulk response item
}

11)批量操作API

BulkProcessor类提供了一个简单的接口,可根据请求的数量或大小自动刷新批量操作,或者在给定时间段之后。

https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.4/java-docs-bulk-processor.html

以上示例代码:https://github.com/bjlhx15/spring-cloud-base/tree/master/service6-es/service2-es-client/src/test/java/com/github/bjlhx15/servicees

008-elasticsearch5.4.3【二】ES使用、ES客户端、索引操作【增加、删除】、文档操作【crud】的更多相关文章

  1. es之java删除文档操作

    删除文档操作 @Test public void deleteDocument(){ DeleteResponse response = client.prepareDelete("twit ...

  2. ES入门三部曲:索引操作,映射操作,文档操作

    ES入门三部曲:索引操作,映射操作,文档操作 一.索引操作 1.创建索引库 #语法 PUT /索引名称 { "settings": { "属性名": " ...

  3. es删除文档或者删除索引

    es删除文档或者删除索引 学习了:https://www.imooc.com/video/15771 删除文档: DELETE http://127.0.0.1:9200/people/man/1 删 ...

  4. es关闭不使用的index、真正删除文档

    因为只要索引处于open状态,就会占用内存+磁盘: 如果将索引close,只会占用磁盘 Curl -XPOST ‘hadoop01:9200/index/_close’ ------ 在es中删除文档 ...

  5. Elasticsearch必知必会的干货知识一:ES索引文档的CRUD

    ​ 若在传统DBMS 关系型数据库中查询海量数据,特别是模糊查询,一般我们都是使用like %查询的值%,但这样会导致无法应用索引,从而形成全表扫描效率低下,即使是在有索引的字段精确值查找,面对海量数 ...

  6. Elasticsearch技术解析与实战(二)文档的CRUD操作

    启动Elasticsearch和kibana 访问Elasticsearch:http://localhost:9200/?pretty 访问kibana:http://localhost:5601 ...

  7. jQuery二——属性操作、文档操作、位置属性

    一.jquery的属性操作 jquery对象有它自己的属性和方法. 其中jquery的属性操作模块分为四个部分:html属性操作,dom属性操作,类样式操作和值操作. 1.html属性操作 是对htm ...

  8. 【Elasticsearch 7 探索之路】(二)文档的 CRUD 和批量操作

    上一篇,我们介绍了什么是 Elasticsearch,它能做什么用以及基本概念(索引 Index.文档 Document.类型 Type)理解.这篇主要对 文档的基本 CRUD 和 倒排索引进行讲解. ...

  9. 〈二〉ElasticSearch的认识:索引、类型、文档

    目录 上节回顾 本节前言 索引index 创建索引 查看索引 查看单个索引 查看所有索引 删除索引 修改索引 修改副本分片数量 关闭索引 索引别名 增加索引别名: 查看索引别名: 删除索引别名: 补充 ...

随机推荐

  1. 2. Docker部署tomcat, nginx, redis,及docker私有仓库

    1. 部署tomcat 1.1 下载tomcat       docker pull tomcat:7-jre8 1.2 部署容器  docker run -di --name=tomcat -p 8 ...

  2. sql 字符串 切割函数 FUN_Split

    IF EXISTS ( SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FUN_Split]') AND OBJECTPROPER ...

  3. Android数据库使用指南(上)

    前言Android上的数据库是sqlite,虽然这个数据库是轻量级的,但是储存的东西可不少,sqlite官方表示理论存储容量为140TB,目前应该没有那么大容量的手机,存储能力太强了. 关于如何使用S ...

  4. Ubuntu18 给terminal改个漂亮的命令行提示符

    重新安装了VMware和Ubuntu,但是命令行提示符太单调,不美观,如何更改呢.于是在网上巴拉巴拉搜寻一番. 1.更改PS1环境变量,这俩都可以,我选择第一个: export PS1="\ ...

  5. 长沙理工大学第十二届ACM大赛-重现赛 J 武藏牌牛奶促销

    链接:https://ac.nowcoder.com/acm/contest/1/J 来源:牛客网 武藏牌牛奶促销 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 131072K,其他 ...

  6. 连续处理函数reduce

    >>> def operat(x,y): return x*y >>> print reduce(operat,(1,2,3,4,5,6,7,8,9,10))362 ...

  7. CDMA原理

    CDMA原理——特点 CDMA具有抗多径干扰.抗窄带干扰.抗认为干扰.抗多径延迟扩展的能力.同时有提高蜂窝系统的通信容量和便于模拟与数字体制的共存与过渡等优点.与TDMA技术形成强劲的竞争力. 与FD ...

  8. HTML中的表单<form>标签

    一.HTML表单 HTML 表单用于搜集不同类型的用户输入. HTML 表单包含表单元素,表单元素指的是不同类型的 input 元素.复选框.单选按钮.提交按钮等等. 关于表单的更多内容可以参考htt ...

  9. SQL把a表字段数据存到b表字段 update,,insert

    update SYS_Navigation set SYS_Navigation.PARENT_XH = SYS_Power_menu.parent_id,SYS_Navigation.web_tit ...

  10. IIS6、IIS7.5设置网站默认首页方法(Directory Listing Denied)

    这篇文章主要介绍了IIS6.IIS7.5设置网站默认首页方法,如果不设置访问目录就会提示Directory Listing Denied,就是不允许列出文档,为了安全网站都会设置不设置默认,需要的朋友 ...