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. 关于Java的三种普通排序

    首先要知道是哪几种排序 这里我们所说的是 冒泡排序,选择排序以及插入排序 然后要理解大概的排序速度 : 插入<选择<冒泡 下面是代码 大家可以拷贝自己在java环境里运行运行! publi ...

  2. java基本框架

    public class 文件名 { public static void mian(string[] args) { 自己的代码: } }

  3. Java会话(session)管理

    会话概述 什么是会话 简单的理解:用户打开浏览器,点击多个超链接,访问Web服务器上多个资源,然后关闭浏览器,整个过程称之为一次会话. 需要解决的问题 每个用户在使用浏览器与服务器会话的过程中,会产生 ...

  4. 122. Best Time to Buy and Sell Stock II@python

    Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...

  5. git命令使用(三)

    git的使用--分支的使用 我们都知道拉取代码的时候,拉下来的是默认的分支,但我们需要的是,其他分支的使用操作 开始,拉取项目 git clone url 查看分支,显示默认分支 git branch ...

  6. JavaScript中的内置函数

    JavaScript中的内置函数 制作人:全心全意 在使用JavaScript语言时,除了可以自定义函数之外,还可以使用JavaScript的内置函数,这些内置函数是由JavaScript语言自身提供 ...

  7. Django框架基础知识09-请求与响应

    视图函数接受到的request到底是个什么对象呢? HttpRequest对象: 服务器接收到http协议的请求后,会根据报文创建HttpRequest对象视图函数的第一个参数是HttpRequest ...

  8. shell for mysql backup in linux

    今天上班只有一台linux系统,就学着在linux上写了个脚本,没啥技术含量 省得每天敲代码备份 没有设置自动备份时间,这里可以参照 http://www.th7.cn/db/mysql/201305 ...

  9. jquery的ajax和getJson跨域获取json数据

    目前浏览器端跨域访问常用的两种方法有两种: 1.通过jQuery的ajax进行跨域,这其实是采用的jsonp的方式来实现的. jsonp是英文json with padding的缩写.它允许在服务器端 ...

  10. 大数据学习——采集目录到HDFS

    采集需求:某服务器的某特定目录下,会不断产生新的文件,每当有新文件出现,就需要把文件采集到HDFS中去 根据需求,首先定义以下3大要素 l  采集源,即source——监控文件目录 :  spoold ...