如何在ubuntu中安装ubuntu elasticsearchh

Linux下Elasticsearch 1.7.0安装配置_服务器应用_Linux公社-Linux系统门户网站
你好,游客
Linux下Elasticsearch 1.7.0安装配置
来源:Linux社区&
作者:Linux
ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。
使用案例:
维基百科使用Elasticsearch来进行全文搜做并高亮显示关键词,以及提供search-as-you-type、did-you-mean等搜索建议功能。
英国卫报使用Elasticsearch来处理访客日志,以便能将公众对不同文章的反应实时地反馈给各位编辑。
StackOverflow将全文搜索与地理位置和相关信息进行结合,以提供more-like-this相关问题的展现。
GitHub使用Elasticsearch来检索超过1300亿行代码。
每天,Goldman Sachs使用它来处理5TB数据的索引,还有很多投行使用它来分析股票市场的变动。
ElasticSearch的优缺点:
1、Elasticsearch是分布式的。不需要其他组件,分发是实时的,被叫做&Push replication&。
2、Elasticsearch 完全支持 Apache Lucene 的接近实时的搜索。
3、处理多租户(multitenancy)不需要特殊配置,而Solr则需要更多的高级设置。
4、Elasticsearch 采用 Gateway 的概念,使得完备份更加简单。
5、各节点组成对等的网络结构,某些节点出现故障时会自动分配其他节点代替其进行工作。
1、还不够自动
2、仅支持json文件格式。
华丽的分割线(以下进入正题)
--------------------------------------分割线 --------------------------------------
1、首先去elasticsearch官网下载软件包版本1.7.0版本.
#wget https://download.elastic.co/elasticsearch/elasticsearch/elasticsearch-1.7.0.tar.gz
2、解压elasticsearch-1.7.0.tar.gz 软件包.
#tar zxf elasticsearch-1.7.0.tar.gz
3、es配置文件参数解释(真正配置不全用的到):
#集群名称标识了你的集群,自动探查会用到它。
#如果你在同一个网络中运行多个集群,那就要确保你的集群名称是独一无二的.
cluster.name: test-elasticsearch
#节点名称会在启动的时候自动生成,所以你可以不用手动配置。你也可以给节点指定一个特定的名称.
node.name: "elsearch1"
#允许这个节点被选举为一个主节点(默认为允许)
#node.master: true
#允许这个节点存储数据(默认为允许)
# node.data: true
#You can exploit these settings to design advanced cluster topologies.
# 你可以利用这些设置设计高级的集群拓扑
# 1. You want this node to never become a master node, only to hold data.
#& & This will be the "workhorse" of your cluster.
# 1. 你不想让这个节点成为一个主节点,只想用来存储数据。
#& & 这个节点会成为你的集群的&负载器&
# node.master: false # node.data: true
#You want this node to only serve as a master: to not store any data and
#& & to have free resources. This will be the "coordinator" of your cluster.
# 2. 你想让这个节点成为一个主节点,并且不用来存储任何数据,并且拥有空闲资源。
#& & 这个节点会成为你集群中的&协调器&
# node.master: true # node.data: false
# Use the Cluster Health API [http://localhost:9200/_cluster/health], the
# Node Info API [http://localhost:9200/_nodes] or GUI tools
#使用集群体检API[http://localhost:9200/_cluster/health] ,
# 节点信息API[http://localhost:9200/_cluster/nodes] 或者GUI工具例如:
# A node can have generic attributes associated with it, which can later be used
# for customized shard allocation filtering, or allocation awareness. An attribute
# is a simple key value pair, similar to node.key: value, here is an example:
# 一个节点可以附带一些普通的属性,这些属性可以在后面的自定义分片分配过滤或者allocation awareness中使用。
# 一个属性就是一个简单的键值对,类似于node.key: value, 这里有一个例子:
# node.rack: rack314
# By default, multiple nodes are allowed to start from the same installation location
# to disable it, set the following:
# 默认的,多个节点允许从同一个安装位置启动。若想禁止这个特性,按照下面所示配置:
# node.max_local_storage_nodes: 1
# Set the number of shards (splits) of an index (5 by default):
# 设置一个索引的分片数量(默认为5)
# index.number_of_shards: 5
# Set the number of replicas (additional copies) of an index (1 by default):
# 设置一个索引的副本数量(默认为1)
# index.number_of_replicas: 1
# Note, that for development on a local machine, with small indices, it usually
# makes sense to "disable" the distributed features:
# 注意,为了使用小的索引在本地机器上开发,禁用分布式特性是合理的做法。
# index.number_of_shards: 1 # index.number_of_replicas: 0
# Path to directory containing configuration (this file and logging.yml):
# 包含配置(这个文件和logging.yml)的目录的路径
# path.conf: /path/to/conf
# Path to directory where to store index data allocated for this node.
# 存储这个节点的索引数据的目录的路径
# path.data: /path/to/data
# Can optionally include more than one location, causing data to be striped across
# the locations (a la RAID 0) on a file level, favouring locations with most free
# space on creation. For example:
# 可以随意的包含不止一个位置,这样数据会在文件层跨越多个位置(a la RAID 0),创建时会
# 优先选择大的剩余空间的位置
# path.data: /path/to/data1,/path/to/data2
# Path to temporary files:
# 临时文件的路径
# path.work: /path/to/work
# Path to log files:
# 日志文件的路径
# path.logs: /path/to/logs
# Path to where plugins are installed:
# 插件安装路径
# path.plugins: /path/to/plugins
# If a plugin listed here is not installed for current node, the node will not start.
# 如果当前结点没有安装下面列出的插件,结点不会启动
# plugin.mandatory: mapper-attachments,lang-groovy
# ElasticSearch performs poorly when JVM starts swapping: you should ensure that
# it _never_ swaps.
# 当JVM开始swapping(换页)时ElasticSearch性能会低下,你应该保证它不会换页
# Set this property to true to lock the memory:
# 设置这个属性为true来锁定内存
# bootstrap.mlockall: true
# Make sure that the ES_MIN_MEM and ES_MAX_MEM environment variables are set
# to the same value, and that the machine has enough memory to allocate
# for ElasticSearch, leaving enough memory for the operating system itself.
# 确保ES_MIN_MEM和ES_MAX_MEM环境变量设置成了同一个值,确保机器有足够的内存来分配
# 给ElasticSearch,并且保留足够的内存给操作系统
# You should also make sure that the ElasticSearch process is allowed to lock
# the memory, eg. by using `ulimit -l unlimited`.
# 你应该确保ElasticSearch的进程可以锁定内存,例如:使用`ulimit -l unlimited`
# ElasticSearch, by default, binds itself to the 0.0.0.0 address, and listens
# on port [] for HTTP traffic and on port [] for node-to-node
# communication. (the range means that if the port is busy, it will automatically
# try the next port).
# 默认的ElasticSearch把自己和0.0.0.0地址绑定,HTTP传输的监听端口在[],节点之间
# 通信的端口在[]。(范围的意思是说如果一个端口已经被占用,它将会自动尝试下一个端口)
# Set the bind address specifically (IPv4 or IPv6):
# 设置一个特定的绑定地址(IPv4 or IPv6):
# network.bind_host: 192.168.0.1
# Set the address other nodes will use to communicate with this node. If not
# set, it is automatically derived. It must point to an actual IP address.
# 设置其他节点用来与这个节点通信的地址。如果没有设定,会自动获取。
# 必须是一个真实的IP地址。
# network.publish_host: 192.168.0.1
# Set both 'bind_host' and 'publish_host':
# 'bind_host'和'publish_host'都设置
# network.host: 192.168.0.1
# Set a custom port for the node to node communication (9300 by default):
# 为节点之间的通信设置一个自定义端口(默认为9300)
# transport.tcp.port: 9300
# Enable compression for all communication between nodes (disabled by default):
# 为所有的节点间的通信启用压缩(默认为禁用)
# transport.tcp.compress: true
# Set a custom port to listen for HTTP traffic:
# 设置一个监听HTTP传输的自定义端口
# http.port: 9200
# Set a custom allowed content length:
# 设置一个自定义的允许的内容长度
# http.max_content_length: 100mb
# Disable HTTP completely:
# 完全禁用HTTP
# http.enabled: false
3、操作系统配置
1.文件描述符
vim /etc/security/limits.conf添加 *& soft nofile 655350 *& hard nofile 655350
退出当前用户重新login就会生效,使用ulimit -n验证下。
2.最大内存映射区数量,禁用swap交换分区
vim /etc/sysctl.conf增加 vm.max_map_count=262144 vm.swappiness=1 & 修改完成后sysctl -p
jvm参数配置
ES_HOME的bin目录下有一个elasticsearch.in.sh文件,修改
& & ES_MIN_MEM=256m & & ES_MAX_MEM=1g
为合适的值
4、es的插件安装:
Marvel是Elasticsearch的管理和监控工具,对于开发使用免费的。它配备了一个叫做Sense的交互式控制台,方便通过浏览器直接与Elasticsearch交互。
Marvel是一个插件,在Elasticsearch目录中运行以下代码来下载和安装:
./plugin -i elasticsearch/marvel/latest
elasticsearch-head是一个elasticsearch的集群管理工具,它是完全由html5编写的独立网页程序,你可以通过插件把它集成到es。
#./plugin -install mobz/elasticsearch-head
地址:http://172.16.2.24:25556/_plugin/head/
elasticsearch插件bigdesk安装:
bigdesk是elasticsearch的一个集群监控工具,可以通过它来查看es集群的各种状态,如:cpu、内存使用情况,索引数据、搜索情况,http连接数等。
在cmd命令行中进入安装目录??再进入 bin目录,运行以下命令:
#./plugin -install lukas-vlcek/bigdesk
在浏览器中输入:http://172.16.2.24:25556/_plugin/bigdesk可以看到效果
注意:elasticsearch 分词ik的安装,如果不安装分词ik插件,根本建不了索引,并且让访问http://172.16.2.24:25556/_plugin/head/ 集群一片空白,点击web 创建索引页没有反应。
注意:github https://github.com/medcl/elasticsearch-analysis-ik 给出了对应的es的ik版本,1.7.0的es对应的1.2.6的版本,开始我这块装了1.8的ik,创建索引失败,后台也是报ik的错误。
ik:1.2.6版本的下载:https://github.com/medcl/elasticsearch-analysis-ik/releases?after=v1.6.1
安装操作:
下载zip包解压到一个目录解压缩:
#unzip elasticsearch-analysis-ik-master.zip
安装mavne环境,apache 官网下载软件包设置环境变量:
#export PATH=$PATH:/usr/local/maven/bin
因为是源代码,此处需要使用maven打包,进入解压文件夹中,执行命令:
#cd elasticsearch-analysis-ik-master #mvn clean package
#在es的plugin目录下创建ik目录,并将target目录下的elasticsearch-analysis-ik-1.2.6.jar copy 到ik目录下。
[root@localhost target]# cd /data/elasticsearch-1.7.0 [root@localhost elasticsearch-1.7.0]# ls bin& config& data& lib& LICENSE.txt& logs& NOTICE.txt& plugins& README.textile [root@localhost elasticsearch-1.7.0]# cd plugins/ [root@localhost plugins]# ls bigdesk& head& ik& marvel [root@localhost plugins]# cd ik/ [root@localhost ik]# ls elasticsearch-analysis-ik-1.2.6.jar
注意:如果是集群,可以将jar分别copy至其他几台机器。
es配置文件需要添加入下行:
index: & analysis:& & & & & & & & & & & & analyzer:& & & & & & ik: & & & & & alias: [ik_analyzer] & & & & & type: org.elasticsearch.index.analysis.IkAnalyzerProvider & & & ik_max_word: & & & & & type: ik & & & & & use_smart: false& & & ik_smart: & & & & & type: ik & & & & & use_smart: truemarvel.agent.enabled: false
完整的es配置文件如下,三台同样的配置,除了hostip和node.name外.
# cat elasticsearch.yml cluster.name: test-es-cluster network.host: 172.16.2.24 node.name: "node24"discovery.zen.ping.unicast.hosts: ["172.16.2.24:25555","172.16.2.21:25555","172.16.2.23:25555"] index.number_of_shards: 5 discovery.zen.minimum_master_nodes: 2 script.groovy.sandbox.enabled: falsetransport.tcp.port: 25555 http.port: 25556 script.inline: off script.indexed: off script.file: off index: & analysis:& & & & & & & & & & & & analyzer:& & & & & & ik: & & & & & alias: [ik_analyzer] & & & & & type: org.elasticsearch.index.analysis.IkAnalyzerProvider & & & ik_max_word: & & & & & type: ik & & & & & use_smart: false& & & ik_smart: & & & & & type: ik & & & & & use_smart: truemarvel.agent.enabled: false
后台启动es服务:
[root@localhost bin]# pwd /data/elasticsearch-1.7.0/bin[root@localhost bin]# ./elasticsearch -d
三台集群的机器中找其中一台创建索引:
创建索引:
curl -X PUT 'http://172.16.2.24:25556/index'{"acknowledged":true}
注意:返回结果为acknowledged":true 为成功.
通过浏览器访问:http://172.16.2.24:25556/_plugin/head/ 测试效果.
Elasticsearch 教程系列文章:&
Linux上安装部署ElasticSearch全程记录&
Elasticsearch安装使用教程
ElasticSearch 配置文件译文解析
ElasticSearch的工作机制& &
Elasticsearch的安装,运行和基本配置
使用Elasticsearch + Logstash + Kibana搭建日志集中分析平台实践&
14.04搭建ELK日志分析系统(Elasticsearch+Logstash+Kibana)
Elasticsearch1.7升级到2.3实践总结&
Ubuntu 14.04中Elasticsearch集群配置&
Elasticsearch-5.0.0移植到Ubuntu 16.04
ElasticSearch 5.2.2 集群环境的搭建&
Linux下安装搜索引擎Elasticsearch&
上安装 ElasticSearch 详解&
ElasticSearch 的详细介绍:ElasticSearch 的下载地址:
本文永久更新链接地址:
相关资讯 & & &
& (06月13日)
& (04月14日)
& (07月12日)
& (05月23日)
& (10/30/:52)
   同意评论声明
   发表
尊重网上道德,遵守中华人民共和国的各项有关法律法规
承担一切因您的行为而直接或间接导致的民事或刑事法律责任
本站管理人员有权保留或删除其管辖留言中的任意内容
本站有权在网站内转载或引用您的评论
参与本评论即表明您已经阅读并接受上述条款云计算&大数据
WEB开发设计
Object Storage
Conceptual
如何在CentOS和Ubuntu中安装Elasticsearch(单节点集群)
Elasticsearch是灵活的,功能强大的开源,分布式实时搜索和分析引擎。使用一个简单的API集,它提供了全文搜索的能力。在Apache 2中弹性搜索免费提供许可,它提供了最大的灵活性。
本教程将帮助你在CentOS,RedHat,Ubuntu,Debian和LinuxMint系统安装Elasticsearch单节点集群。
Java是用于安装Elasticsearch的主要要求。因此,请确保你已经在系统上安装了Java。
# java -version
java version "1.8.0_31"
Java(TM) SE Runtime Environment (build 1.8.0_31-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.31-b07, mixed mode)
如果您没有在系统上安装Java,使用下面的一个环节先安装它。
现在,从下载最新的Elasticsearch存档。在这篇文章中Elasticsearch 2.3.1版本的最后一次更新的时间是最新的版本可供下载。
$ wget https://download.elastic.co/elasticsearch/elasticsearch/elasticsearch-2.3.1.tar.gz
现在,提取您的系统上下载的存档Elasticsearch。
$ tar xzf elasticsearch-2.3.1.tar.gz
现在,我们需要设置Elasticsearch集群和节点名称。 Elasticsearch 使用“elasticsearch“作为默认群集名称,我们建议根据您的设置改变它。
$ mv elasticsearch-2.3.1 /usr/share/elasticsearch
$ cd /usr/share/elasticsearch
要更改以下值集群命名编辑config/elasticsearch.yml文件并更新。节点名称是动态生成的,但为了保持一个固定的用户友好的名称。您可能还需要从远程主机更改网络主机访问elasticsearch。
$ vim config/elasticsearch.yml
network.host: 192.168.10.100
cluster.name: HowToing_Cluster1
node.name: "California DataCenter"
$ bin/plugin install mobz/elasticsearch-head
Elasticsearch安装完成。让我们启动Elasticsearch集群,使用以下命令。
$ ./bin/elasticsearch &
你已经全部完成,只需要验证设置。 Elasticsearch工作在端口默认端口9200,打开浏览器指向端口9200的服务器,你会发现有些东西,像下面的输出
http://localhost:9200/_plugin/head/
http://svt1.howtoing.com:9200/
下面的例子将帮助你在Elasticsearch集群添加,获取和检索数据。
curl -XPUT http://localhost:9200/mybucket
{"acknowledged":true}
使用下面的命令来在Elasticsearch添加一些数据。
curl -XPUT 'http://localhost:9200/mybucket/user/johny' -d '{ "name" : "Rahul Kumar" }'
{"_index":"mybucket","_type":"user","_id":"johny","_version":1,"created":true}
curl -XPUT 'http://localhost:9200/mybucket/post/1' -d '
"user": "Rahul",
"postDate": "01-15-2015",
"body": "This is Demo Post 1 in Elasticsearch" ,
"title": "Demo Post 1"
{"_index":"mybucket","_type":"post","_id":"1","_version":1,"created":true}
curl -XPUT 'http://localhost:9200/mybucket/post/2' -d '
"user": "HowToing",
"postDate": "01-15-2015",
"body": "This is Demo Post 2 in Elasticsearch" ,
"title": "Demo Post 2"
{"_index":"mybucket","_type":"post","_id":"2","_version":1,"created":true}
使用以下命令从ElasticSearch获取数据,读取输出。
curl -XGET 'http://localhost:9200/mybucket/user/johny?pretty=true'
curl -XGET 'http://localhost:9200/mybucket/post/1?pretty=true'
curl -XGET 'http://localhost:9200/mybucket/post/2?pretty=true'
使用以下命令从弹性搜索中搜索数据。下面的命令将搜索与用户关联和Johny所有数据。
curl 'http://localhost:9200/mybucket/post/_search?q=user:HowToing&pretty=true'
"took" : 145,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
"hits" : {
"total" : 1,
"max_score" : 0.,
"hits" : [ {
"_index" : "mybucket",
"_type" : "post",
"_id" : "2",
"_score" : 0.,
"_source":
"user": "HowToing",
"postDate": "01-15-2015",
"body": "This is Demo Post 2 in Elasticsearch" ,
"title": "Demo Post 2"
祝贺您!您已成功在Linux系统上安装配置elasticsearch单节点集群。
文章分类 10
howtoing.com是一个运维教程站,开始于2012年5月。这里提供如何简单的学习引导Linux/Windows系统管理员的目标。我们一直在努力提供简单易学高质量的文章。
(C)2017 Howtoing运维教程 京ICP备号-1ElasticSearch安装和使用
时间: 19:50:33
&&&& 阅读:830
&&&& 评论:
&&&& 收藏:0
标签:&&&&&&&&&&&&&&&&&&&&&&&&&&&  ElasticSearch是开源搜索平台的新成员,实时数据分析的神器。可以理解为作为搜索的数据库,可以提供搜索功能。对比关系型数据库,具有以下的相似关系:
关系型数据库
ElasticSearch
  一个ES集群可以包含多个索引(数据库),每个索引又包含了很多类型(表),类型中包含了很多文档(行),每个文档又包含了很多字段(列)。
  如果要实现对关系型数据库数据的搜索功能,需要将关系型数据库中的数据导入到ElasticSearch中,网上有解决方案。但是好像不支持最新的ElasticSearch5,可以使用我下面的Java代码实现数据的导入。
Ubuntu系统安装 Elasticsearch5
升级系统后安装
Java 7,既然 Elasticsearch 官方推荐使用 Oracle JDK 7 就不要尝试 JDK 8 和 OpenJDK 了:
1 $ sudo apt-get update
2 $ sudo apt-get upgrade
4 $ sudo apt-get install software-properties-common
5 $ sudo add-apt-repository ppa:webupd8team/java
6 $ sudo apt-get update
8 $ sudo apt-get install oracle-java7-installer
加入 Elasticsearch 官方源后安装 elasticsearch:
1 $ wget -O - http://packages.elasticsearch.org/GPG-KEY-elasticsearch | apt-key add -
2 $ sudo echo "deb http://packages.elasticsearch.org/elasticsearch/1.1/debian stable main" && /etc/apt/sources.list
4 $ sudo apt-get update
5 $ sudo apt-get install elasticsearch
加入到系统启动文件并启动 elasticsearch 服务,用 curl 测试一下安装是否成功:
1 $ sudo update-rc.d elasticsearch defaults 95 1
3 $ sudo /etc/init.d/elasticsearch start
5 $ curl -X GET ‘http://localhost:9200‘
"status" : 200,
"name" : "Fer-de-Lance",
"version" : {
"number" : "1.1.1",
"build_hash" : "ffdebdc1abbc",
"build_timestamp" : "T14:27:12Z",
"build_snapshot" : false,
"lucene_version" : "4.7"
"tagline" : "You Know, for Search"
Elasticsearch 的集群和数据管理界面 Marvel 非常赞,可惜只对开发环境免费,安装很简单,完成后重启服务访问 http://192.168.2.172:9200/_plugin/marvel/ 就可以看到界面:
1 $ sudo /usr/share/elasticsearch/bin/plugin -i elasticsearch/marvel/latest
3 $ sudo /etc/init.d/elasticsearch restart
* Stopping Elasticsearch Server
* Starting Elasticsearch Server
另外可以安装elasticsearch-head作为管理Elasticsearch的web前端插件。
安装教程:
ElasticSearch Java调用
&  命令调用的方式不再讲述了,网上很多。ElasticSearch最终是要在项目中使用的。官方的API文档:
&自己写了助手类,方便大家调用。可以实现索引的增删改查,查询提供多种方法,包括or、and查询,多个关键词查询,关键词高亮等,适用于不同场合。
首先是引用需要的jar包。使用maven管理jar包,需要的jar包有:
&dependency&
&groupId&org.elasticsearch&/groupId&
&artifactId&elasticsearch&/artifactId&
&version&5.3.1&/version&
&/dependency&
&dependency&
&groupId&org.elasticsearch.client&/groupId&
&artifactId&transport&/artifactId&
&version&5.3.1&/version&
&/dependency&
&dependency&
&groupId&org.apache.logging.log4j&/groupId&
&artifactId&log4j-api&/artifactId&
&version&2.7&/version&
&/dependency&
&dependency&
&groupId&org.apache.logging.log4j&/groupId&
&artifactId&log4j-core&/artifactId&
&version&2.7&/version&
&/dependency&
然后是ElasticSearch配置文件,存储集群名称、集群IP、索引名称。配置文件命名为:elasticsearch.properties
cluster_name=elasticsearch
cluster_serverip=127.0.0.1
indexname=blogsystem
还需要配置日志配置文件,命名为:log4j2.properties
appender.console.type = Console
appender.console.name = console
appender.console.layout.type = PatternLayout
rootLogger.level = info
rootLogger.appenderRef.console.ref = console
最后是java的实现ElasticSearch助手类。为了方便使用,助手类分为具体实现和调用两个类。
ElasticSearch具体实现类:ElasticSearchUtilsImp.java
1 package com.blog.
3 import java.io.IOE
4 import java.io.InputS
5 import java.lang.reflect.M
6 import java.net.InetA
7 import java.net.UnknownHostE
8 import java.util.ArrayL
9 import java.util.HashM
10 import java.util.L
11 import java.util.M
12 import java.util.P
13 import java.util.concurrent.ExecutionE
15 import org.elasticsearch.action.delete.DeleteR
16 import org.elasticsearch.action.index.IndexR
17 import org.elasticsearch.action.search.SearchRequestB
18 import org.elasticsearch.action.search.SearchR
19 import org.elasticsearch.action.update.UpdateR
20 import org.elasticsearch.client.transport.TransportC
21 import org.elasticsearch.common.settings.S
22 import org.elasticsearch.common.text.T
23 import org.elasticsearch.common.transport.InetSocketTransportA
24 import org.elasticsearch.common.xcontent.XContentB
25 import org.elasticsearch.common.xcontent.XContentF
26 import org.elasticsearch.index.query.BoolQueryB
27 import org.elasticsearch.index.query.QueryB
28 import org.elasticsearch.index.query.QueryB
29 import org.elasticsearch.rest.RestS
30 import org.elasticsearch.search.SearchH
31 import org.elasticsearch.search.aggregations.AggregationB
32 import org.elasticsearch.search.fetch.subphase.highlight.HighlightB
33 import org.elasticsearch.search.fetch.subphase.highlight.HighlightF
34 import org.elasticsearch.transport.client.PreBuiltTransportC
* @author:Tim
* @date:日 下午8:24:22
* @description:ElasticSearch助手类具体实现
41 public class ElasticSearchUtilsImp {
private static String cluster_name = null;// 实例名称
private static String cluster_serverip = null;// elasticSearch服务器ip
private static String indexname = null;// 索引名称
// 读取db.properties文件
Properties props = new Properties();
InputStream in = ElasticSearchUtilsImp.class.getResourceAsStream("/elasticsearch.properties");
props.load(in);// 加载文件
// 读取信息
cluster_name = props.getProperty("cluster_name");
cluster_serverip = props.getProperty("cluster_serverip");
indexname = props.getProperty("indexname");
} catch (IOException e) {
e.printStackTrace();
System.out.println("加载数据库配置文件出错!");
* 返回一个到ElasticSearch的连接客户端
private static TransportClient getClient() {
Settings settings = Settings.builder().put("cluster.name", cluster_name).build();// 设置集群名称
@SuppressWarnings("unchecked")
TransportClient client = new PreBuiltTransportClient(settings);// 创建client
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(cluster_serverip), 9300));// 增加地址和端口
} catch (UnknownHostException e) {
e.printStackTrace();
System.out.println("ElasticSearch连接失败!");
* 将Map转换成builder
* @param mapParam
* @throws Exception
private static XContentBuilder createMapJson(Map&String, String& mapParam) throws Exception {
XContentBuilder source = XContentFactory.jsonBuilder().startObject();
for (Map.Entry&String, String& entry : mapParam.entrySet()) {
source.field(entry.getKey(), entry.getValue());
source.endObject();
* 将实体转换成json
* @param entity 实体
* @param fieldNameParm 实体中待转换成json的字段
* @return 返回json
* @throws Exception
private static XContentBuilder createEntityJson(Object entity, String... methodNameParm) throws Exception {
// 创建json对象, 其中一个创建json的方式
XContentBuilder source = XContentFactory.jsonBuilder().startObject();
for (String methodName : methodNameParm) {
if (!methodName.startsWith("get")) {
throw new Exception("不是有效的属性!");
Method method = entity.getClass().getMethod(methodName, null);
String fieldValue = (String) method.invoke(entity, null);
String fieldName = StringUtils.toLowerCaseFirstOne(methodName.replace("get", ""));// 去掉&get&,并将首字母小写
// 避免和elasticSearch中id字段重复
if (fieldName == "_id") {
fieldName = "id";
source.field(fieldName, fieldValue);
} catch (NoSuchMethodException e) {
e.printStackTrace();
System.out.println("未找到方法!");
source.endObject();
* 将一个Map格式的数据(key,value)插入索引 (私有方法)
* @param type 类型(对应数据库表)
* @param docId id,对应elasticSearch中的_id字段
* @param mapParam Map格式的数据
public static boolean addMapDocToIndex(String type, String docId, Map&String, String& mapParam) {
boolean result = false;
TransportClient client = getClient();
XContentBuilder source = null;
source = createMapJson(mapParam);
} catch (Exception e) {
e.printStackTrace();
// 存json入索引中
IndexResponse response = null;
if (docId == null) {
// 使用默认的id
response = client.prepareIndex(indexname, type).setSource(source).get();
response = client.prepareIndex(indexname, type, docId).setSource(source).get();
// 插入结果获取
String index = response.getIndex();
String gettype = response.getType();
String id = response.getId();
long version = response.getVersion();
RestStatus status = response.status();
String strResult = "新增文档成功:" + index + " : " + gettype + ": " + id + ": " + version + ": " + status.getStatus();
System.out.println(strResult);
if (status.getStatus() == 201) {
result = true;
// 关闭client
client.close();
* 将一个实体存入到默认索引的类型中(指定_id,一般是业务数据的id,及elasticSearch和关系型数据使用同一个id,方便同关系型数据库互动)
* (私有方法)
* @param type 类型(对应数据库表)
* @param docId id,对应elasticSearch中的_id字段
* @param entity 要插入的实体
* @param methodNameParm 需要将实体中哪些属性作为字段
public static boolean addEntityDoc(String type, String docId, Object entity, String... methodNameParm) {
boolean result = false;
TransportClient client = getClient();
XContentBuilder source = null;
source = createEntityJson(entity, methodNameParm);
} catch (Exception e) {
e.printStackTrace();
// 存json入索引中
IndexResponse response = null;
if (docId == null) {
// 使用默认的id
response = client.prepareIndex(indexname, type).setSource(source).get();
response = client.prepareIndex(indexname, type, docId).setSource(source).get();
// 插入结果获取
String index = response.getIndex();
String gettype = response.getType();
String id = response.getId();
long version = response.getVersion();
RestStatus status = response.status();
String strResult = "新增文档成功:" + index + " : " + gettype + ": " + id + ": " + version + ": " + status.getStatus();
System.out.println(strResult);
if (status.getStatus() == 201) {
result = true;
// 关闭client
client.close();
* 删除文档
* @param type 类型(对应数据库表)
* @param docId 类型中id
public static boolean deleteDoc(String type, String docId) {
boolean result = false;
TransportClient client = getClient();
DeleteResponse deleteresponse = client.prepareDelete(indexname, type, docId).get();
System.out.println("删除结果:" + deleteresponse.getResult().toString());
if (deleteresponse.getResult().toString() == "DELETED") {
result = true;
// 关闭client
client.close();
* 修改文档
* @param type 类型
* @param docId 文档id
* @param updateParam 需要修改的字段和值
public static boolean updateDoc(String type, String docId, Map&String, String& updateParam) {
String strResult = "";
boolean result = false;
TransportClient client = getClient();
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index(indexname);
updateRequest.type(type);
updateRequest.id(docId);
updateRequest.doc(createMapJson(updateParam));
} catch (Exception e) {
e.printStackTrace();
strResult = client.update(updateRequest).get().getResult().toString();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
System.out.println(strResult);
if (strResult == "UPDATED") {
result = true;
* TODO or查询命中条数
* @param type 类型
* @param shouldMap 查询条件
public static int multiOrSearchDocCount(String type, Map&String, String& shouldMap) {
TransportClient client = getClient();
* 高亮搜索
* @param type 类型
* @param fieldName 段
* @param keyword 关键词
* @param from 开始行数
* @param size 每页大小
public static Map&String, Object& searchDocHighlight(String type, String fieldName, String keyword, int from,
int size) {
TransportClient client = getClient();
HighlightBuilder hiBuilder = new HighlightBuilder();
hiBuilder.preTags("&span style=\"color:red\"&");
hiBuilder.postTags("&/span&");
hiBuilder.field(fieldName);
QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(fieldName, keyword);
SearchRequestBuilder responsebuilder = client.prepareSearch(indexname).setTypes(type);
responsebuilder.setQuery(queryBuilder);
responsebuilder.highlighter(hiBuilder);
responsebuilder.setFrom(from);
responsebuilder.setSize(size);
responsebuilder.setExplain(true);
SearchResponse myresponse = responsebuilder.execute().actionGet();
SearchHits searchHits = myresponse.getHits();
// 总命中数
long total = searchHits.getTotalHits();
Map&String, Object& map = new HashMap&String, Object&();
map.put("total", total);
List&Map&String, Object&& list = new ArrayList&Map&String, Object&&();
for (int i = 0; i & searchHits.getHits(). i++) {
Map&String, HighlightField& highlightFields = searchHits.getHits()[i].getHighlightFields();
HighlightField titleField = highlightFields.get(fieldName);
Map&String, Object& source = searchHits.getHits()[i].getSource();
if (titleField != null) {
Text[] fragments = titleField.fragments();
String name = "";
for (Text text : fragments) {
source.put(fieldName, name);
list.add(source);
map.put("rows", list);
* or条件查询高亮
* @param type 类型
* @param shouldMap or条件和值
* @param from 开始行数
* @param size 每页大小
public static Map&String, Object& multiOrSearchDocHigh(String type, Map&String, String& shouldMap, int from,
int size) {
TransportClient client = getClient();
SearchRequestBuilder responsebuilder = client.prepareSearch(indexname).setTypes(type);
responsebuilder.setFrom(from);
responsebuilder.setSize(size);
responsebuilder.setExplain(true);
HighlightBuilder hiBuilder = new HighlightBuilder();
hiBuilder.preTags("&span style=\"color:red\"&");
hiBuilder.postTags("&/span&");
// 高亮每个字段
for (String key : shouldMap.keySet()) {
hiBuilder.field(key);
responsebuilder.highlighter(hiBuilder);
if (null != shouldMap && shouldMap.size() & 0) {
// 创建一个查询
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
// 这里查询的条件用map传递
for (String key : shouldMap.keySet()) {
queryBuilder.should(QueryBuilders.matchPhraseQuery(key, shouldMap.get(key)));// or连接条件
responsebuilder.setQuery(queryBuilder);
SearchResponse myresponse = responsebuilder.execute().actionGet();
SearchHits searchHits = myresponse.getHits();
// 总命中数
long total = searchHits.getTotalHits();
Map&String, Object& map = new HashMap&String, Object&();
map.put("total", total);
List&Map&String, Object&& list = new ArrayList&Map&String, Object&&();
for (int i = 0; i & searchHits.getHits(). i++) {
Map&String, HighlightField& highlightFields = searchHits.getHits()[i].getHighlightFields();
Map&String, Object& source = searchHits.getHits()[i].getSource();
for (String key : shouldMap.keySet()) {
// 各个段进行高亮
HighlightField titleField = highlightFields.get(key);
if (titleField != null) {
Text[] fragments = titleField.fragments();
String name = "";
for (Text text : fragments) {
source.put(key, name);
list.add(source);
map.put("rows", list);
* @param type 类型
* @param fieldName 待搜索的字段
* @param keyword 待搜索的关键词
* @param from 开始行数
* @param size 每页大小
public static Map&String, Object& searchDoc(String type, String fieldName, String keyword, int from, int size) {
List&String& hitResult = new ArrayList&String&();
TransportClient client = getClient();
QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery(fieldName, keyword);
SearchRequestBuilder responsebuilder = client.prepareSearch(indexname).setTypes(type);
responsebuilder.setQuery(queryBuilder);
responsebuilder.setFrom(from);
responsebuilder.setSize(size);
responsebuilder.setExplain(true);
SearchResponse myresponse = responsebuilder.execute().actionGet();
SearchHits hits = myresponse.getHits();
for (int i = 0; i & hits.getHits(). i++) {
hitResult.add(hits.getHits()[i].getSourceAsString());
// 将命中结果转换成Map输出
Map&String, Object& modelMap = new HashMap&String, Object&(2);
modelMap.put("total", hitResult.size());
modelMap.put("rows", hitResult);
return modelM
* 多个条件进行or查询
* @param type 类型
* @param shouldMap 进行or查询的段和值
* @param from 开始行数
* @param size 每页大小
public static Map&String, Object& multiOrSearchDoc(String type, Map&String, String& shouldMap, int from, int size) {
List&String& hitResult = new ArrayList&String&();
TransportClient client = getClient();
SearchRequestBuilder responsebuilder = client.prepareSearch(indexname).setTypes(type);
responsebuilder.setFrom(from);
responsebuilder.setSize(size);
responsebuilder.setExplain(true);
if (null != shouldMap && shouldMap.size() & 0) {
// 创建一个查询
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
// 这里查询的条件用map传递
for (String key : shouldMap.keySet()) {
queryBuilder.should(QueryBuilders.matchPhraseQuery(key, shouldMap.get(key)));// or连接条件
responsebuilder.setQuery(queryBuilder);
SearchResponse myresponse = responsebuilder.execute().actionGet();
SearchHits hits = myresponse.getHits();
for (int i = 0; i & hits.getHits(). i++) {
hitResult.add(hits.getHits()[i].getSourceAsString());
// 将命中结果转换成Map输出
Map&String, Object& modelMap = new HashMap&String, Object&(2);
modelMap.put("total", hitResult.size());
modelMap.put("rows", hitResult);
return modelM
* 多个条件进行and查询
* @param type 类型
* @param mustMap 进行and查询的段和值
* @param from 开始行数
* @param size 每页大小
public static Map&String, Object& multiAndSearchDoc(String type, Map&String, String& mustMap, int from, int size) {
List&String& hitResult = new ArrayList&String&();
TransportClient client = getClient();
SearchRequestBuilder responsebuilder = client.prepareSearch(indexname).setTypes(type);
responsebuilder.setFrom(from);
responsebuilder.setSize(size);
responsebuilder.setExplain(true);
if (null != mustMap && mustMap.size() & 0) {
// 创建一个查询
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
// 这里查询的条件用map传递
for (String key : mustMap.keySet()) {
queryBuilder.must(QueryBuilders.matchPhraseQuery(key, mustMap.get(key)));// and查询
responsebuilder.setQuery(queryBuilder);
SearchResponse myresponse = responsebuilder.execute().actionGet();
SearchHits hits = myresponse.getHits();
for (int i = 0; i & hits.getHits(). i++) {
hitResult.add(hits.getHits()[i].getSourceAsString());
// 将命中结果转换成Map输出
Map&String, Object& modelMap = new HashMap&String, Object&(2);
modelMap.put("total", hitResult.size());
modelMap.put("rows", hitResult);
return modelM
ElasticSearchUtilsImp.java
ElasticSearch调用类,是对实现类的各种组合,供外部调用。调用类名称:ElasticSearchUtils.java
1 package com.blog.
3 import java.util.M
* @author:Tim
* @date:日 下午8:24:22
* @description:ElasticSearch助手类
10 public class ElasticSearchUtils {
* 将一个Map格式的数据(key,value)插入索引(指定_id,一般是业务数据的id,及elasticSearch和关系型数据使用同一个id,方便同关系型数据库互动)
* @param type 类型(对应数据库表)
* @param docId id,对应elasticSearch中的_id字段
* @param mapParam Map格式的数据
public static boolean addDoc(String type, String docId, Map&String, String& mapParam) {
return ElasticSearchUtilsImp.addMapDocToIndex(type, docId, mapParam);
* 将一个Map格式的数据(key,value)插入索引 (使用默认_id)
* @param type 类型(对应数据库表)
* @param mapParam Map格式的数据
public static boolean addDoc(String type, Map&String, String& mapParam) {
return ElasticSearchUtilsImp.addMapDocToIndex(type, null, mapParam);
* 将一个实体存入到默认索引的类型中(默认_id)
* @param type 类型(对应数据库表)
* @param entity 要插入的实体
* @param methodNameParm 需要将实体中哪些属性作为字段
public static boolean addDoc(String type, Object entity, String... methodNameParm) {
return ElasticSearchUtilsImp.addEntityDoc(type, null, entity, methodNameParm);
* 将一个实体存入到默认索引的类型中(指定_id,一般是业务数据的id,及elasticSearch和关系型数据使用同一个id,方便同关系型数据库互动)
* @param type 类型(对应数据库表)
* @param docId id,对应elasticSearch中的_id字段
* @param entity 要插入的实体
* @param methodNameParm 需要将实体中哪些属性作为字段
public static boolean addDoc(String type, String docId, Object entity, String... methodNameParm) {
return ElasticSearchUtilsImp.addEntityDoc(type, docId, entity, methodNameParm);
* 删除文档
* @param type 类型(对应数据库表)
* @param docId 类型中id
public static boolean deleteDoc(String type, String docId) {
return ElasticSearchUtilsImp.deleteDoc(type, docId);
* 修改文档
* @param type 类型
* @param docId 文档id
* @param updateParam 需要修改的字段和值
public static boolean updateDoc(String type, String docId, Map&String, String& updateParam) {
return ElasticSearchUtilsImp.updateDoc(type, docId, updateParam);
// --------------------以下是各种搜索方法--------------------------
* 高亮搜索
* @param type 类型
* @param fieldName 段
* @param keyword 段值
public static Map&String, Object& searchDocHighlight(String type, String fieldName, String keyword) {
return ElasticSearchUtilsImp.searchDocHighlight(type, fieldName, keyword, 0, 10);
* 高亮搜索
* @param type 类型
* @param fieldName 段
* @param keyword 关键词
* @param from 开始行数
* @param size 每页大小
public static Map&String, Object& searchDocHighlight(String type, String fieldName, String keyword, int from,
int size) {
return ElasticSearchUtilsImp.searchDocHighlight(type, fieldName, keyword, from, size);
* or条件查询高亮
* @param type 类型
* @param shouldMap or条件和值
public static Map&String, Object& multiOrSearchDocHigh(String type, Map&String, String& shouldMap, int from,
int size) {
return ElasticSearchUtilsImp.multiOrSearchDocHigh(type, shouldMap, from, size);
* @param type 类型
* @param fieldName 待搜索的字段
* @param keyword 待搜索的关键词
public static Map&String, Object& searchDoc(String type, String fieldName, String keyword) {
return ElasticSearchUtilsImp.searchDoc(type, fieldName, keyword, 0, 10);
* 多个条件进行or查询
* @param type 类型
* @param shouldMap 进行or查询的段和值
public static Map&String, Object& multiOrSearchDoc(String type, Map&String, String& shouldMap) {
return ElasticSearchUtilsImp.multiOrSearchDoc(type, shouldMap, 0, 10);
* 多个条件进行and查询
* @param type 类型
* @param mustMap 进行and查询的段和值
public static Map&String, Object& multiAndSearchDoc(String type, Map&String, String& mustMap) {
return ElasticSearchUtilsImp.multiAndSearchDoc(type, mustMap, 0, 10);
会使用到的其他助手类:StringUtils.java
1 package com.blog.
3 import java.util.M
5 import net.sf.json.JSONO
* @author:Tim
* @date:日 上午11:56:37
* @description:字符串助手类
12 public class StringUtils {
* 将Map转换成json字符串
* @param map Map&String, Object&格式数据
* @return json数据
public static String map2String(Map&String, Object& map) {
return JSONObject.fromObject(map).toString();
* 首字母转小写
* @param s 待转换的字符串
public static String toLowerCaseFirstOne(String s) {
if (Character.isLowerCase(s.charAt(0)))
return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
StringUtils.java
具体的使用在我的另一个项目中有使用实例,该项目使用这个助手类实现了索引的各种操作,以及搜索展现功能。项目位置:标签:&&&&&&&&&&&&&&&&&&&&&&&&&&&原文地址:http://www.cnblogs.com/yangtze-yufei/p/6821716.html
&&国之画&&&& &&&&chrome插件&&
版权所有 京ICP备号-2
迷上了代码!}

我要回帖

更多关于 searchsploit ubuntu 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信