java elasticsearch 索引如何对两个索引进行关联查询

elasticsearch的实现全文检索 | 赵岩的博客elasticsearch5.2.2怎么用java api创建索引_百度知道
elasticsearch5.2.2怎么用java api创建索引
答题抽奖
首次认真答题后
即可获得3次抽奖机会,100%中奖。
育知同创教育知道合伙人
百度知道合伙人官方认证企业
育知同创教育
知道合伙人
1、【专注:Python+人工智能|Java大数据|HTML5培训】。 2、【免费提供名师直播课堂、公开课及视频教程】。 3、【地址:北京市昌平区三旗百汇物美大卖场2层,微信公众号:yuzhitc】
下面的例子把json文档写入所以,索引库名为twitter、类型为tweet,id为1: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();也可以直接传人JSON字符串:String json = &{& +&\&user\&:\&kimchy\&,& +&\&postDate\&:\&\&,& +&\&message\&:\&trying out Elasticsearch\&& +&}&;IndexResponse response = client.prepareIndex(&twitter&, &tweet&).setSource(json).get();可以调用response对象的方法获取返回信息:// 索引名称String _index = response.getIndex();// 类型名称String _type = response.getType();// 文档idString _id = response.getId();// 版本(if it's the first time you index this document, you will get: 1)long _version = response.getVersion();// 是否被创建is true if the document is a new one, false if it has been updatedboolean created = response.isCreated();
为你推荐:
其他类似问题
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。[Elasticsearch] 邻近匹配 (三) - 性能,关联单词查询以及Shingles
短语和邻近度查询比简单的match查询在性能上更昂贵。match查询只是查看词条是否存在于倒排索引(Inverted Index)中,而match_phrase查询则需要计算和比较多个可能重复词条(Multiple possibly repeated)的位置。
在Lucene Nightly Benchmarks中,显示了一个简单的term查询比一个短语查询快大概10倍,比一个邻近度查询(一个拥有slop的短语查询)快大概20倍。当然,这个代价是在搜索期间而不是索引期间付出的。
通常,短语查询的额外代价并不像这些数字说的那么吓人。实际上,性能上的差异只是说明了一个简单的term查询时多么的快。在标准全文数据上进行的短语查询通常能够在数毫秒内完成,因此它们在实际生产环境下是完全能够使用的,即使在一个繁忙的集群中。
在某些特定的场景下,短语查询可能会很耗费资源,但是这种情况时不常有的。一个典型的例子是DNA序列,此时会在很多位置上出现非常之多的相同重复词条。使用高slop值会使位置计算发生大幅度的增长。
因此,如何能够限制短语和邻近度查询的性能消耗呢?一个有用的方法是减少需要使用短语查询进行检查的文档总数。
结果的分值重计算(Rescoring
在上一节中,我们讨论了使用邻近度查询来调整相关度,而不是使用它来将文档从结果列表中添加或者排除。一个查询可能会匹配百万计的结果,但是我们的用户很可能只对前面几页结果有兴趣。
一个简单的match查询已经通过排序将含有所有搜索词条的文档放在结果列表的前面了。而我们只想对这些前面的结果进行重新排序来给予那些同时匹配了短语查询的文档额外的相关度。
search API通过分值重计算(Rescoring)来支持这一行为。在分值重计算阶段,你能够使用一个更加昂贵的分值计算算法 - 比如一个短语查询 - 来为每个分片的前K个结果重新计算其分值。紧接着这些结果就会按其新的分值重新排序。
该请求如下所示:
GET /my_index/my_type/_search
"query": {
"match": {
"title": {
"quick brown fox",
"minimum_should_match": "30%"
"rescore": {
"window_size": 50,
"query": {
"rescore_query": {
"match_phrase": {
"title": {
"query": "quick brown fox",
match查询用来决定哪些文档会被包含在最终的结果集合中,结果通过TF/IDF进行排序。 window_size是每个分片上需要重新计算分值的数量。
寻找关联的单词(Finding Associated Words)
尽管短语和邻近度查询很管用,它们还是有一个缺点。它们过于严格了:所有的在短语查询中的词条都必须出现在文档中,即使使用了slop。
通过slop获得的能够调整单词顺序的灵活性也是有代价的,因为你失去了单词之间的关联。尽管你能够识别文档中的sue,alligator和ate出现在一块,但是你不能判断是Sue ate还是alligator ate。
当单词结合在一起使用时,它们表达的意思比单独使用时要丰富。"I’m not happy I’m working"和"I’m happy I’m not working"含有相同的单词,也拥有相近的邻近度,但是它们的意思大相径庭。
如果我们索引单词对,而不是索引独立的单词,那么我们就能够保留更多关于单词使用的上下文信息。
对于句子"Sue ate the alligator",我们不仅索引每个单词(或者Unigram)为一个词条:
["sue", "ate", "the", "alligator"]
我们同时会将每个单词和它的邻近单词一起索引成一个词条:
["sue ate", "ate the", "the alligator"]
这些单词对(也叫做Bigram)就是所谓的Shingle。
Shingle不限于只是单词对;你也可以索引三个单词(Word Triplet,也被称为Trigram)作为一个词条:
["sue ate the", "ate the alligator"]
Trigram能够给你更高的精度,但是也大大地增加了索引的不同词条的数量。在多数情况下,Bigram就足够了。
当然,只有当用户输入查询的顺序和原始文档的顺序一致,Shingle才能够起作用;一个针对sue alligator的查询会匹配单独的单词,但是不会匹配任何Shingle。
幸运的是,用户会倾向于使用和他们正在搜索的数据中相似的结构来表达查询。但是这是很重要的一点:仅使用Bigram是不够的;我们仍然需要Unigram,我们可以将匹配Bigram作为信号(Signal)来增加相关度分值。
产生Shingle
Shingle需要在索引期间,作为分析过程的一部分被创建。我们可以将Unigram和Bigram都索引到一个字段中,但是将它们放在不同的字段中会更加清晰,也能够让它们能够被独立地查询。Unigram字段形成了我们搜索的基础部分,而Bigram字段则用来提升相关度。
首先,我们需要使用shingle词条过滤器来创建解析器:
DELETE /my_index
PUT /my_index
"settings": {
"number_of_shards": 1,
"analysis": {
"filter": {
"my_shingle_filter": {
"shingle",
"min_shingle_size": 2,
"max_shingle_size": 2,
"output_unigrams":
"analyzer": {
"my_shingle_analyzer": {
"tokenizer":
"standard",
"filter": [
"lowercase",
"my_shingle_filter"
默认Shingle的min/max值就是2,因此我们也可以不显式地指定它们。 output_unigrams被设置为false,用来避免将Unigram和Bigram索引到相同字段中。
让我们使用analyze API来测试该解析器:
GET /my_index/_analyze?analyzer=my_shingle_analyzer
Sue ate the alligator
不出所料,我们得到了3个词条:
sue ateate thethe alligator
现在我们就可以创建一个使用新解析器的字段了。
多字段(Multifields)
将Unigram和Bigram分开索引会更加清晰,因此我们将title字段创建成一个多字段(Multifield)(参见字符串排序和多字段(String
Sorting and Multifields)):
PUT /my_index/_mapping/my_type
"my_type": {
"properties": {
"title": {
"type": "string",
"fields": {
"shingles": {
"analyzer": "my_shingle_analyzer"
有了上述映射,JSON文档中的title字段会以Unigram(title字段)和Bigram(title.shingles字段)的方式索引,从而让我们可以独立地对这两个字段进行查询。
最后,我们可以索引示例文档:
POST /my_index/my_type/_bulk
{ "index": { "_id": 1 }}
{ "title": "Sue ate the alligator" }
{ "index": { "_id": 2 }}
{ "title": "The alligator ate Sue" }
{ "index": { "_id": 3 }}
{ "title": "Sue never goes anywhere without her alligator skin purse" }
搜索Shingles
为了理解添加的shingles字段的好处,让我们首先看看一个针对"The hungry alligator ate Sue"的简单match查询的返回结果:
GET /my_index/my_type/_search
"query": {
"match": {
"title": "the hungry alligator ate sue"
该查询会返回所有的3份文档,但是注意文档1和文档2拥有相同的相关度分值,因为它们含有相同的单词:
"_id": "1",
"_score": 0.,
"_source": {
"title": "Sue ate the alligator"
"_id": "2",
"_score": 0.,
"_source": {
"title": "The alligator ate Sue"
"_id": "3",
"_score": 0.,
"_source": {
"title": "Sue never goes anywhere without her alligator skin purse"
现在让我们将shingles字段也添加到查询中。记住我们会将shingle字段作为信号 - 以增加相关度分值 - 我们仍然需要将主要的title字段包含到查询中:
GET /my_index/my_type/_search
"query": {
"match": {
"title": "the hungry alligator ate sue"
"should": {
"match": {
"title.shingles": "the hungry alligator ate sue"
我们仍然匹配了3分文档,但是文档2现在排在了第一位,因为它匹配了Shingle词条"ate sue":
"_id": "2",
"_score": 0.4883322,
"_source": {
"title": "The alligator ate Sue"
"_id": "1",
"_score": 0.,
"_source": {
"title": "Sue ate the alligator"
"_id": "3",
"_score": 0.,
"_source": {
"title": "Sue never goes anywhere without her alligator skin purse"
即使在查询中包含了没有在任何文档中出现的单词hungry,我们仍然通过使用单词邻近度得到了最相关的文档。
Shingle不仅比短语查询更灵活,它们的性能也更好。相比每次搜索需要为短语查询付出的代价,对Shingle的查询和简单match查询一样的高效。只是在索引期间会付出一点小代价,因为更多的词条需要被索引,意味着使用了Shingle的字段也会占用更多的磁盘空间。但是,多数应用是写入一次读取多次的,因此在索引期间花费一点代价来让查询更迅速是有意义的。
这是一个你在ES中经常会碰到的主题:让你在搜索期间能够做很多事情,而不需要任何预先的设置。一旦更好地了解了你的需求,就能够通过在索引期间正确地建模来得到更好的结果和更好的性能。索引 - ElasticSearch基本使用
时间: 19:53:38
&&&& 阅读:873
&&&& 评论:
&&&& 收藏:0
标签:&&&&&&&&&&&&&&&&&&&&&&&&&&&
ElasticSearch是一个基于Lucene的搜索服务器;
它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口;
Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎(阿里巴巴、Google、京东等都在使用);
设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便;
我们建立一个网站或应用程序,并要添加搜索功能,但是想要完成搜索工作的创建是非常困难的。我们希望搜索解决方案要运行速度快,我们希望能有一个零配置和一个完全免费的搜索模式,我们希望能够简单地使用JSON通过HTTP来索引数据,我们希望我们的搜索服务器始终可用,我们希望能够从一台开始并扩展到数百台,我们要实时搜索,我们要简单的多租户,我们希望建立一个云的解决方案。因此我们利用Elasticsearch来解决所有这些问题以及可能出现的更多其它问题;
ElasticSearch-5.6.4 ()
elasticsearch-head (ElasticSearch插件 )
Node.js-v8.9.0
1 . 上传下载好的软件,如下
2 . 安装和配置好JDK和Node.js
自行Google或百度
3 . 解压好ElasticSearch
配置ElasticSearch
[ local]# vim ./elasticsearch-5.6.4/config/elasticsearch.yml
注意:ElasticSearch是不允许root用户启动的,所以需要使用其他用户来进行启动操作,以下是新的用户组和用户的创建:
[ bin]$ useradd tandi
# 新增一个用户tandi
[ bin]$ passwd tandi
# 修改用户tandi的密码
[ bin]$ groupadd elastic
# 新增一个用户组elastic
[ bin]$ usermod -a -G elastic tandi
# 将用户tandi添加到组elastic中
[ bin]$ chown -R tandi:elastic elasticsearch-5.6.4
# 将elasticsearch-6.1.1/权限给elastic组tandi这个用户
[ bin]$ su tandi
# 切换到tandi用户
[ bin]$ ./elasticsearch -d
# 后台运行ElasticSearch
可以使用命令jps来查看是否运行成功,成功如下:
[ bin]$ jps
32268 Elasticsearch
问题:[1]: max file descriptors [4096] for elasticsearch process is too low, increase to at least [65536]
解决方法:
[ local]# vim /etc/security/limits.conf
在文件后追加以下内容:
问题:[2]: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]
解决方法:
[ local]# vim /etc/sysctl.conf
在文件后追加以下内容:
vm.max_map_count=655360
其余问题参考以下文章和自行Google或百度
elasticsearch-5.1.1 安装的问题
CentOS7上elasticsearch5.5启动报错
该插件的作用是让ElasticSearch在浏览器的操作界面更加友好
首选解压elasticsearch-head
[ myfile]# unzip elasticsearch-head-master.zip
进入elasticsearch-head-master使用nmp命令进行安装操作
[ elasticsearch-head-master]# npm install
提示:如果npm安装依赖慢,建议将npm设置为国内镜像,又或者直接在主机中安装该插件,如下:
浏览器访问head插件
配置ElasticSearch让其和head插件关联起来
[ config]# vim elasticsearch.yml
在文本最后追加以下内容,并重启ElasticSearch:
http.cors.enabled: true
http.cors.allow-origin: "*"
浏览器中使用head插件连接ElasticSearch
以当前ElasticSearch作为源复制三分到elasticsearch-cluster文件夹中,如下:
切记:如果使用之前已有数据的ElasticSearch复制,复制完后记得删除各个ElasticSearch中的data目录,否者集群不成功!!!(问题:http://blog.csdn.net/qq_/article/details/)
master配置不用动,其余两个从节点配置大体相同(slave1配置如下):
启动过程中可能会出现问题:Java HotSpot(TM) 64-Bit Server VM warning: INFO: os::commit_memory
原因:因为三个elasticsearch在同一台虚拟机中运行,这是系统内存不足所致,elasticsearch启动内容默认为2G
[ elasticsearch-cluster]# vim elasticsearch-master/config/jvm.options
[ elasticsearch-cluster]# vim elasticsearch-slave1/config/jvm.options
[ elasticsearch-cluster]# vim elasticsearch-slave2/config/jvm.options
对索引的基本理解
* 索引:可以理解为书的目录(目录=索引)
* 类型:索引的类型,可以理解为目录中的分类标题
* 文档:类型下的具体内容
结合下图理解(个人理解):
参考官方文档,如下:()
自定义例子(postman):
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1
"mappings": {
"properties": {
"type": "text"
"country": {
"type": "keyword"
"type": "integer"
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
"woman": {
"superman": {
注意:以上设置都不是必须自己设置的,现在尝试创建一个只指定索引名称但不写任何结构的索引,看看是什么情况
请求URL: 192.168.229.100:9200/peoplex
以下是自动生成的索引结构
"state": "open",
"settings":
"creation_date": "3",
"number_of_shards": "5",
"number_of_replicas": "1",
"uuid": "tThX8Af3TyWFjA0FJjIsnw",
"version":
"created": "5060499"
"provided_name": "peoplex"
"mappings":
"aliases": [],
"primary_terms":
"in_sync_allocations":
"z7DpqK6OROa9XbYNgQPOWQ",
"54ZWMzLHQoyMPfxh1nE69A"
"LCIDY_G5R1SLhi2mOWUOWw",
"uzBW-bxfSiSgJVfeqkI49A"
"J1m9dQ2NQvykqr12Fg5EYw",
"8anEJ_TOSyGMoeJU0p_C5w"
"SKhsMMwjR4iQxXvrhsvyGg",
"vBibauuNSIe-k0dqEQuqLQ"
"AhfRDd6tTDKr20kU02WnoA",
"_eFgNTl3SuecNu79ZbVLSw"
和ElasticSearch交互:
不指定id:
删除文档:
删除索引:
删除文档:
/////////////////1
/////////////////2
/////////////////3
获取指定id文档
多字段查找
表达式查找
数据返回格式参照
//URL get请求返回数据格式 (192.168.229.100:9200/people/man/AWCDzUmToHzKzvfCjwMr)
"_index": "people",
"_type": "man",
"_id": "AWCDzUmToHzKzvfCjwMr",
"_version": 1,
"found": true,
"_source": {
"name": "李四",
"age": 23,
"country": "加拿大",
"date": ""
//post请求返回数据格式(以下为分组查找的响应格式)
"took": 25,
"timed_out": false,
"_shards": {
"total": 3,
"successful": 3,
"skipped": 0,
"failed": 0
"total": 12,
"max_score": 1,
"_index": "people",
"_type": "man",
"_id": "AWCD6XPXoHzKzvfCjwMx",
"_score": 1,
"_source": {
"name": "赵四",
"age": 19,
"country": "泰国",
"date": ""
"_index": "people",
"_type": "man",
"_id": "AWCEAQFYoHzKzvfCjwMz",
"_score": 1,
"_source": {
"name": "王中天",
"age": 19,
"country": "中国",
"date": ""
"_index": "people",
"_type": "man",
"_id": "AWCDzOc0oHzKzvfCjwMq",
"_score": 1,
"_source": {
"name": "张三",
"age": 21,
"country": "美国",
"date": ""
"_index": "people",
"_type": "man",
"_id": "AWCDzUmToHzKzvfCjwMr",
"_score": 1,
"_source": {
"name": "李四",
"age": 23,
"country": "加拿大",
"date": ""
"_index": "people",
"_type": "man",
"_id": "AWCIbziXASUp1WxfELkt",
"_score": 1,
"_source": {
"name": "桃白白",
"age": 19,
"country": "泰国",
"date": ""
"_index": "people",
"_type": "man",
"_id": "AWCIb6WVASUp1WxfELku",
"_score": 1,
"_source": {
"name": "谭迪",
"country": "泰国",
"date": ""
"_index": "people",
"_type": "man",
"_id": "AWCDzjLYoHzKzvfCjwMs",
"_score": 1,
"_source": {
"name": "王五",
"age": 18,
"country": "泰国",
"date": ""
"_index": "people",
"_type": "man",
"_id": "AWCD1meEoHzKzvfCjwMv",
"_score": 1,
"_source": {
"name": "王五2",
"age": 18,
"country": "泰国",
"date": ""
"_index": "people",
"_type": "man",
"_id": "AWCD1pHToHzKzvfCjwMw",
"_score": 1,
"_source": {
"name": "赵四",
"age": 18,
"country": "泰国",
"date": ""
"_index": "people",
"_type": "man",
"_id": "AWCIBMplASUp1WxfELkj",
"_score": 1,
"_source": {
"name": "谭迪",
"age": 88,
"country": "中国",
"date": null
"aggregations": {
"以date分组": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
"key_as_string": " 00:00:00",
"doc_count": 8
"key_as_string": " 00:00:00",
"doc_count": 1
"key_as_string": " 00:00:00",
"doc_count": 1
"以age分组": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
"key": 19,
"doc_count": 4
"key": 18,
"doc_count": 3
"key": 21,
"doc_count": 2
"doc_count": 1
"key": 23,
"doc_count": 1
"key": 88,
"doc_count": 1
以上都是些较为简单的例子,推荐参考以下资料来学习
ElasticSearch权威指南: structured-search.html
ElasticSearch 常用的查询过滤语句:
使用java client api基本使用
快速入门案例:spring boot + maven + elasticsearch
项目目录结构:
以下为主要代码和配置:
&?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.td&/groupId&
&artifactId&estest&/artifactId&
&version&0.0.1-SNAPSHOT&/version&
&packaging&jar&/packaging&
&name&estest&/name&
&description&&/description&
&groupId&org.springframework.boot&/groupId&
&artifactId&spring-boot-starter-parent&/artifactId&
&version&1.5.9.RELEASE&/version&
&relativePath/& &!-- lookup parent from repository --&
&!-- 属性 --&
&properties&
&project.build.sourceEncoding&UTF-8&/project.build.sourceEncoding&
&project.reporting.outputEncoding&UTF-8&/project.reporting.outputEncoding&
&java.version&1.8&/java.version&
&/properties&
&!-- 依赖 --&
&dependencies&
&dependency&
&groupId&org.springframework.boot&/groupId&
&artifactId&spring-boot-starter-web&/artifactId&
&/dependency&
&dependency&
&groupId&org.springframework.boot&/groupId&
&artifactId&spring-boot-starter-test&/artifactId&
&scope&test&/scope&
&/dependency&
&!-- elasticSearch --&
&dependency&
&groupId&org.elasticsearch&/groupId&
&artifactId&elasticsearch&/artifactId&
&version&6.1.1&/version&
&/dependency&
&dependency&
&groupId&org.elasticsearch.client&/groupId&
&artifactId&transport&/artifactId&
&version&6.1.1&/version&
&/dependency&
&dependency&
&groupId&org.apache.logging.log4j&/groupId&
&artifactId&log4j-core&/artifactId&
&version&2.9.1&/version&
&/dependency&
&!-- lang3 --&
&dependency&
&groupId&org.apache.commons&/groupId&
&artifactId&commons-lang3&/artifactId&
&version&3.4&/version&
&/dependency&
&/dependencies&
&groupId&org.springframework.boot&/groupId&
&artifactId&spring-boot-maven-plugin&/artifactId&
&/plugins&
&/project&
public class People {
//{"date":"","country":"中国","name":"谭迪","age":21}
public People() {
public String getName() {
public void setName(String name) {
this.name =
public int getAge() {
public void setAge(int age) {
this.age =
public String getCountry() {
public void setCountry(String country) {
this.country =
public String getDate() {
public void setDate(String date)throws Exception{
this.date =
public String toString() {
return "People{" +
"name=‘" + name + ‘\‘‘ +
", age=" + age +
", country=‘" + country + ‘\‘‘ +
", date=" + date +
configuration(spring4-javaConfig):
@Configuration
public class ESJavaConfig {
* 返回ElasticSearch 客户端api对象
* @throws Exception
public TransportClient client()throws Exception {
Settings.Builder builder = Settings.builder();
builder.put("cluster.name", "ElasticSearchCluster"); //集群名称
builder.put("client.transport.sniff", true); //开启嗅探(简单来说就是你不用配置集群中所有的es的ip,开启嗅探后将会自动查找)
builder.put("client.transport.ignore_cluster_name", false); //是否忽略集群名称校验
builder.put("client.transport.ping_timeout", "5s"); //超时时间
builder.put("client.transport.nodes_sampler_interval", "5s");
//取样时间(刷新)
Settings settings = builder.build();
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.229.100"), 9300));
controller:
@RestController
public class ESController {
@Autowired
TransportC
* URL id查询
* @param id
@GetMapping("/get/people/{id}")
public ResponseEntity findPeopleById(@PathVariable("id") String id){
//使用客户单向es发出查找请求
GetRequestBuilder getRequestBuilder = client.prepareGet("people", "man", id);
//获取es响应结果对象
GetResponse response = getRequestBuilder.get();
//向浏览器返回json格式的结果
return new ResponseEntity(response.getSource(), HttpStatus.OK);
* 接受表单形式参数来创建文档
* @param people
* @throws Exception
@PostMapping("/post/people")
public ResponseEntity addPeople(People people) throws Exception {
//创建json构建对象XContentBuilder,并构建json
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
.startObject()
.field("name", people.getName())
.field("age", people.getAge())
.field("country", people.getCountry())
.field("date", people.getDate())
.endObject();
//使用客户端想es发出创建文档请求
IndexResponse indexResponse = client.prepareIndex("people", "man")
.setSource(xContentBuilder)
//向浏览器返回json格式的结果
return new ResponseEntity(indexResponse.getId(), HttpStatus.OK);
* 接受json串形式参数创建对象
* @param json
* @throws Exception
@PostMapping ("/post/json2people")
public ResponseEntity addJson2People(@RequestBody String json) throws Exception {
//将json串转为pojo
People people = JsonUtils.jsonToPojo(json, People.class);
//创建json构建对象XContentBuilder,并构建json
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
.startObject()
.field("name", people.getName())
.field("age", people.getAge())
.field("country", people.getCountry())
.field("date", people.getDate()+"")
.endObject();
//使用客户端想es发出创建文档请求
IndexResponse indexResponse = client.prepareIndex("people", "man")
.setSource(xContentBuilder) //将构建好的文档json对象发送给es
//获取es响应结果对象IndexResponse
//向浏览器返回json格式的结果
return new ResponseEntity(indexResponse.getId(), HttpStatus.OK);
* 根据id删除文档
* @param id
@DeleteMapping("/delete/people/{id}")
public ResponseEntity deletePeopleById(@PathVariable("id") String id){
//使用客户端向es发出删除请求,并返回响应删除请求的结果对象DeleteRequestBuilder
DeleteRequestBuilder deleteRequestBuilder = client.prepareDelete("people", "man", id);
//从DeleteRequestBuilder中获取请求结果
DeleteResponse deleteResponse = deleteRequestBuilder.get();
//向浏览器返回json格式的结果
return new ResponseEntity(deleteResponse.getId(), HttpStatus.OK);
* 接受表单形式参数来修改指定id的文档
* @param id
* @param json
* @throws Exception
@PutMapping("/update/people/{id}")
public ResponseEntity updatePeopleById(@PathVariable("id") String id, @RequestBody String json) throws Exception{
//将json串转为pojo对象
People people = JsonUtils.jsonToPojo(json, People.class);
//创建更新请求对象
UpdateRequest updateRequest = new UpdateRequest("people", "man", id);
//创建构建json对象的XContentBuilder
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder();
xContentBuilder.startObject(); //构建开始
if( people.getName() != null ){
xContentBuilder.field("name", people.getName());
if ( people.getCountry() != null ){
xContentBuilder.field("country", people.getCountry());
if ( people.getDate() != null ){
xContentBuilder.field("date", people.getDate());
if ( people.getAge() != 0 ){
xContentBuilder.field("age", people.getAge());
xContentBuilder.endObject(); //构建结束
//将构建好的json对象添加到更新请求对象中
UpdateRequest request = updateRequest.doc(xContentBuilder);
//使用客户端想es发出更新请求,并返回请求结果
UpdateResponse updateResponse = client.update(request).get();
//向浏览器返回json格式的结果
return new ResponseEntity(updateResponse.getId(), HttpStatus.OK);
附加一段复合查询代码(不属于上面项目)
@PostMapping("query/book/novel")
public ResponseEntity query( @RequestParam(value = "gt_word_count", defaultValue = "0") int gtWordCount
, @RequestParam(value = "author", required =false) String author
, @RequestParam(value = "title", required =false) String title
, @RequestParam(value = "lt_word_count", required = false) Integer ltWordCount) {
//使用QueryBuilders构建 bool查询构建对象 并返回BoolQueryBuilder
BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
if (author != null) {
//must相当于sql中的and
boolBuilder.must( QueryBuilders.matchQuery("author", author ) );
if (title != null) {
boolBuilder.must( QueryBuilders.matchQuery("title", title ) );
if (bookBean.getTitle() != null) {
builder.must( QueryBuilders.matchQuery("title", bookBean.getTitle()) );
//使用QueryBuilders构建 range范围查询构建对象 并返回RangeQueryBuilder
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("word_count").from(gtWordCount);
if (ltWordCount != null) {
rangeQuery.to(ltWordCount);
//将 range范围查询构建对象 作为过滤条件添加进 bool查询构建对象
boolBuilder.filter(rangeQuery);
//使用客户端向es发出查找请求,并返回 查找请求构建对象
SearchRequestBuilder builder = this.client.prepareSearch("book")
.setTypes("novel") //查找的是 novel 类型
.setSearchType(SearchType.QUERY_THEN_FETCH) //设置检索类型(参考文章:http://www.linuxidc.com/Linux/248.htm)
.setQuery(boolBuilder)
//设入 查询构建对象(内包含着整个查询要求)
.setFrom(0) //从索引0开始查找
.setSize(10); //查找到索引10
//打印es响应的 查找请求构建对象
log.info(String.valueOf(builder));
//从响应中过去请求响应结果
SearchResponse response = builder.get();
//创建一个存放查找结果的容器
List&Map&String,Object&& result = new ArrayList&&();
//遍历查找的的hits集合【java8 lambda表达式】
response.getHits().forEach((s)-&result.add(s.getSource()));
//将查找结果返回给浏览器
return new ResponseEntity(result, HttpStatus.OK);
标签:&&&&&&&&&&&&&&&&&&&&&&&&&&&原文地址:https://www.cnblogs.com/tandi/p/8119522.html
&&国之画&&&& &&&&chrome插件
版权所有 京ICP备号-2
迷上了代码!}

我要回帖

更多关于 elasticsearch 索引 的文章

更多推荐

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

点击添加站长微信