ElasticSearch(5.5.2)在java中的使用

https://blog.csdn.net/didiaodeabing/article/details/79310710

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>

<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.stono</groupId>
<artifactId>es01</artifactId>
<version>1.0-SNAPSHOT</version> <name>es01</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties> <dependencies>
<!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.5.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/transport -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.5.1</version>
</dependency> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
</dependency>
</dependencies> <build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

java:

package com.stono;

import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; public class ElasticSearchTest {
public final static String HOST = "127.0.0.1";
public final static int PORT = 9300;
private TransportClient client = null; @Before
public void getConnect() throws UnknownHostException {
client = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddresses(
new InetSocketTransportAddress(InetAddress.getByName(HOST), PORT)
);
System.out.println("连接信息:" + client.toString());
} @After
public void closeConnect() {
if (null != client) {
System.out.println("执行关闭连接操作");
client.close();
}
} // 使用XContentBuilder创建索引
@Test
public void addIndex() throws IOException {
System.out.println("测试中,使用XContentBuilder创建索引");
/*
建立文档对象
参数一blog1: 表示索引对象
参数二article: 类型
参数三1: 建立id
*/
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.field("id", 1)
.field("title", "elasticSearch引擎")
.field("content", "全球搜索服务器")
.endObject();
IndexResponse indexResponse = client.prepareIndex("blog1", "article", Integer.toString(1)).setSource(builder).get();
// 结果获取
String index = indexResponse.getIndex();
String type = indexResponse.getType();
String id = indexResponse.getId();
long version = indexResponse.getVersion();
RestStatus status = indexResponse.status();
System.out.println("索引:" + index + "; 类型:" + type + "; id:" + id + "; 版本:" + version + "; 状态:" + status);
} // 使用JSON创建索引
@Test
public void addIndex2() throws IOException {
System.out.println("测试中,使用JSON创建索引");
String json = "{" +
"\"name\":\"深入浅出Node.js\"," +
"\"author\":\"朴灵 \"," +
"\"pubinfo\":\"人民邮电出版社 \"," +
"\"pubtime\":\"2013-12-1 \"," +
"\"desc\":\"本书从不同的视角介绍了 Node 内在的特点和结构。由首章Node 介绍为索引,涉及Node 的各个方面,主要内容包含模块机制的揭示、异步I/O 实现原理的展现、异步编程的探讨、内存控制的介绍、二进制数据Buffer 的细节、Node 中的网络编程基础、Node 中的Web 开发、进程间的消息传递、Node 测试以及通过Node 构建产品需要的注意事项。最后的附录介绍了Node 的安装、调试、编码规范和NPM 仓库等事宜。本书适合想深入了解 Node 的人员阅读。\"" +
"}";
IndexResponse indexResponse = client.prepareIndex("blog2", "goods").setSource(json).get();
// 结果获取
String index = indexResponse.getIndex();
String type = indexResponse.getType();
String id = indexResponse.getId();
long version = indexResponse.getVersion();
RestStatus status = indexResponse.status();
System.out.println("索引:" + index + "; 类型:" + type + "; id:" + id + "; 版本:" + version + "; 状态:" + status); } // 使用Map创建索引
@Test
public void addIndex3() throws IOException {
System.out.println("测试中,使用Map创建索引");
Map<String, Object> map = new HashMap<>();
map.put("name", "Go Web编程");
map.put("author", "谢孟军 ");
map.put("pubinfo", "电子工业出版社");
map.put("pubtime", "2013-6");
map.put("desc", "《Go Web编程》介绍如何使用Go语言编写Web,包含了Go语言的入门、Web相关的一些知识、Go中如何处理Web的各方面设计(表单、session、cookie等)、数据库以及如何编写GoWeb应用等相关知识。通过《Go Web编程》的学习能够让读者了解Go的运行机制,如何用Go编写Web应用,以及Go的应用程序的部署和维护等,让读者对整个的Go的开发了如指掌。");
IndexResponse indexResponse = client.prepareIndex("blog2", "goods").setSource(map).execute().actionGet();
// 结果获取
String index = indexResponse.getIndex();
String type = indexResponse.getType();
String id = indexResponse.getId();
long version = indexResponse.getVersion();
RestStatus status = indexResponse.status();
System.out.println("索引:" + index + "; 类型:" + type + "; id:" + id + "; 版本:" + version + "; 状态:" + status); } // 删除索引
// @Test
public void deleteByObject() throws Exception {
DeleteResponse deleteResponse = client.delete(new DeleteRequest("blog1", "article", Integer.toString(1))).get();
} // 获取文档信息
@Test
public void getIndexNoMapping() throws Exception {
GetResponse actionGet = client.prepareGet("blog1", "article", "1").execute().actionGet();
System.out.println(actionGet.getSourceAsString());
} // 查询所有文档信息
@Test
public void getMatchAll() throws IOException {
SearchResponse searchResponse = client.prepareSearch("blog1")
.setTypes("article").setQuery(QueryBuilders.matchAllQuery())
.get(); // get() === execute().actionGet()
// 获取命中次数,查询结果有多少对象
SearchHits hits = searchResponse.getHits();
System.out.println("查询结果有:" + hits.getTotalHits() + "条");
Iterator<SearchHit> iterator = hits.iterator();
while (iterator.hasNext()) {
// 查询每个对象
SearchHit searchHit = iterator.next();
System.out.println(searchHit.getSourceAsString()); // 获取字符串格式打印
System.out.println("title:" + searchHit.getSource().get("title"));
}
} // 关键字查询
@Test
public void getKeyWord() throws IOException {
long time1 = System.currentTimeMillis();
SearchResponse searchResponse = client.prepareSearch("blog1")
.setTypes("article").setQuery(QueryBuilders.queryStringQuery("你们"))
.get();
// 获取命中次数,查询结果有多少对象
SearchHits hits = searchResponse.getHits();
System.out.println("查询结果有:" + hits.getTotalHits() + "条");
Iterator<SearchHit> iterator = hits.iterator();
while (iterator.hasNext()) {
// 查询每个对象
SearchHit searchHit = iterator.next();
// 获取字符串格式打印
System.out.println(searchHit.getSourceAsString());
System.out.println("title:" + searchHit.getSource().get("title"));
}
long time2 = System.currentTimeMillis();
System.out.println("花费" + (time2 - time1) + "毫秒");
} // 通配符、词条查询
@Test
public void getByLike() throws IOException {
long time1 = System.currentTimeMillis();
SearchResponse searchResponse = client.prepareSearch("blog1")
.setTypes("article").setQuery(QueryBuilders.wildcardQuery("desc", "你们*")) // 通配符查询
.setTypes("article").setQuery(QueryBuilders.wildcardQuery("content", "服务器"))
.setTypes("article").setQuery(QueryBuilders.termQuery("content", "全文")) // 词条查询
// 一般情况下只显示十条数据
// from + size must be less than or equal to: [10000]
// Scroll Search 支持1万以上的数据量
// .setSize(10000)
.get();
// 获取命中次数,查询结果有多少对象
SearchHits hits = searchResponse.getHits();
System.out.println("查询结果有:" + hits.getTotalHits() + "条");
Iterator<SearchHit> iterator = hits.iterator();
while (iterator.hasNext()) {
// 查询每个对象
SearchHit searchHit = iterator.next();
// 获取字符串格式打印
System.out.println(searchHit.getSourceAsString());
System.out.println("title:" + searchHit.getSource().get("title"));
}
long time2 = System.currentTimeMillis();
System.out.println("花费" + (time2 - time1) + "毫秒");
} // 组合查询
@Test
public void combinationQuery() throws Exception {
SearchResponse searchResponse = client.prepareSearch("blog1").setTypes("article")
.setQuery(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("title", "搜索"))// 词条查询
// .must(QueryBuilders.rangeQuery("id").from(1).to(5)) // 范围查询
// 因为IK分词器,在存储的时候将英文都转成了小写
.must(QueryBuilders.wildcardQuery("content", "Rest*".toLowerCase())) // 模糊查询
.must(QueryBuilders.queryStringQuery("服电风扇丰盛的电器")) // 关键字(含有)
).get();
SearchHits hits = searchResponse.getHits();
System.out.println("总记录数:" + hits.getTotalHits());
Iterator<SearchHit> iterator = hits.iterator();
while (iterator.hasNext()) {
SearchHit searchHit = iterator.next();
System.out.println(searchHit.getSourceAsString());
Map<String, Object> source = searchHit.getSource();
System.out.println(source.get("id") + ";" + source.get("title") + ";" + source.get("content"));
} } }

ElasticSearch(5.5.2)在java中的使用的更多相关文章

  1. elasticsearch系列七:ES Java客户端-Elasticsearch Java client(ES Client 简介、Java REST Client、Java Client、Spring Data Elasticsearch)

    一.ES Client 简介 1. ES是一个服务,采用C/S结构 2. 回顾 ES的架构 3. ES支持的客户端连接方式 3.1 REST API ,端口 9200 这种连接方式对应于架构图中的RE ...

  2. elasticsearch(一):JAVA api操作

    1.创建一个mavan项目,项目的以来配置如下. <?xml version="1.0" encoding="UTF-8"?> <projec ...

  3. Java中RunTime类介绍

    Runtime 类代表着Java程序的运行时环境,每个Java程序都有一个Runtime实例,该类会被自动创建,我们可以通过Runtime.getRuntime() 方法来获取当前程序的Runtime ...

  4. Elasticsearch 2.3.2 从oracle中同步数据

    Elasticsearch 2.3.2 从oracle中同步数据   1         数据批量导入-oracle 采用 elasticsearch-jdbc 插件 安装.版本需要ES版本一致 最新 ...

  5. 【Elasticsearch】【WEB】java web服务连接es elasticsearch始终报错,无法正常连接使用的错误解决历程

    前情提要: web服务往华为云上迁移 ================内网的好环境,相关配置=================== 1.web服务关于ES的集群配置如下: elasticAddress ...

  6. Java 中为什么要设计包装类

    尽人事,听天命.博主东南大学硕士在读,热爱健身和篮球,乐于分享技术相关的所见所得,关注公众号 @ 飞天小牛肉,第一时间获取文章更新,成长的路上我们一起进步 本文已收录于 「CS-Wiki」Gitee ...

  7. java中的锁

    java中有哪些锁 这个问题在我看了一遍<java并发编程>后尽然无法回答,说明自己对于锁的概念了解的不够.于是再次翻看了一下书里的内容,突然有点打开脑门的感觉.看来确实是要学习的最好方式 ...

  8. java中的字符串相关知识整理

    字符串为什么这么重要 写了多年java的开发应该对String不陌生,但是我却越发觉得它陌生.每学一门编程语言就会与字符串这个关键词打不少交道.看来它真的很重要. 字符串就是一系列的字符组合的串,如果 ...

  9. Java中的Socket的用法

                                   Java中的Socket的用法 Java中的Socket分为普通的Socket和NioSocket. 普通Socket的用法 Java中的 ...

随机推荐

  1. 7-Java-C(冰雹数)

    题目描述: 任意给定一个正整数N, 如果是偶数,执行: N / 2 如果是奇数,执行: N * 3 + 1 生成的新的数字再执行同样的动作,循环往复. 通过观察发现,这个数字会一会儿上升到很高, 一会 ...

  2. Perl: hash散列转换为Json报错集, perl.c,v $$Revision: 4.0.1.8 $$Date: 1993/02/05 19:39:30 $

    bash-2.03$ ./u_json.pl Can't locate object method "encode" via package "JSON" at ...

  3. 第1节 flume:10、flume的更多组件介绍

    作业:flume如何实现收集mysql的数据,没隔几秒钟,查看mysql中的数据是否有变化,一旦有变化,把数据拿过来,存到hdfs上. 需要使用custom source.可网上搜索,github上.

  4. Java编程:常见问题汇总

    每天在写Java程序,其实里面有一些细节大家可能没怎么注意,这不,有人总结了一个我们编程中常见的问题.虽然一般没有什么大问题,但是最好别这样做. AD: 每天在写Java程序,其实里面有一些细节大家可 ...

  5. springmvc下载那些事

    文件的上传下载一般在项目中还是非常实用的,此处专门整理一下文件的下载,至于文件的上传实现将在后续中补上.文件的下载多用于模板文件的下载,这在项目中用的还是挺多的.今天用到了就整理出来了,以供搬运工们借 ...

  6. oracle数字返回为字符串时小时点前面的0缺失的问题

    SELECT 0.001||'' from dual UNION SELECT TO_CHAR(0.001||'','fm999990.99999') from dual;

  7. js|jquery常用代码

    页面重定位: window.location.replace("http://www.bczs.net"); window.location.href = "http:/ ...

  8. Linux基础学习-RHEL7.4之YUM更换CentOS源

    1.配置YUM本地源 1.挂载镜像 [root@qdlinux ~]# mount /dev/cdrom /mnt 2.查看是否挂载成功 [root@qdlinux ~]# df -h Filesys ...

  9. html/css:简单网页

    html: <!DOCTYPE html> <html> <head> <meta http-equiv=“content-type” content=“te ...

  10. Python数据可视化库-Matplotlib(一)

    今天我们来学习一下python的数据可视化库,Matplotlib,是一个Python的2D绘图库 通过这个库,开发者可以仅需要几行代码,便可以生成绘图,直方图,功率图,条形图,错误图,散点图等等 废 ...