├── .gitignore
├── LICENSE
├── README.md
├── pom.xml
└── src
├── main
├── java
│ └── net
│ │ └── aimeizi
│ │ └── spring
│ │ └── data
│ │ └── elasticsearch
│ │ └── example
│ │ ├── Author.java
│ │ ├── Book.java
│ │ ├── repository
│ │ └── BookRepository.java
│ │ └── service
│ │ ├── BookService.java
│ │ └── impl
│ │ └── BookServiceImpl.java
├── resources
│ ├── applicationContext.xml
│ └── logback.xml
└── webapp
│ └── WEB-INF
│ └── web.xml
└── test
└── java
└── net
└── aimeizi
└── spring
└── data
└── elasticsearch
└── example
└── repository
└── test
└── BookRepositoryTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | *.class
2 | .classpath
3 | .project
4 | .settings
5 | target
6 |
7 | # Mobile Tools for Java (J2ME)
8 | .mtj.tmp/
9 |
10 | # Package Files #
11 | *.jar
12 | *.war
13 | *.ear
14 |
15 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
16 | hs_err_pid*
17 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2014 雪山飞鹄
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
23 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | spring-data-elasticsearch-example
2 | =================================
3 |
4 | Spring Data Elasticsearch Example
5 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 |
5 | net.aimeizi
6 | spring-data-elasticsearch-example
7 | war
8 | 1.0
9 |
10 | spring-data-elasticsearch-example
11 | http://maven.apache.org
12 |
13 |
14 |
15 |
16 | javax.servlet
17 | servlet-api
18 | 2.5
19 | provided
20 |
21 |
22 | javax.servlet.jsp
23 | jsp-api
24 | 2.1
25 | provided
26 |
27 |
28 | org.springframework.data
29 | spring-data-elasticsearch
30 | 1.3.0.RELEASE
31 |
32 |
33 | junit
34 | junit
35 | 4.11
36 |
37 |
38 | org.springframework
39 | spring-test
40 | 4.1.0.RELEASE
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 | org.apache.maven.plugins
49 | maven-compiler-plugin
50 | 2.0.2
51 |
52 | 1.7
53 | 1.7
54 |
55 |
56 |
57 | org.apache.tomcat.maven
58 | tomcat6-maven-plugin
59 | 2.2
60 |
61 |
62 | org.apache.tomcat.maven
63 | tomcat7-maven-plugin
64 | 2.2
65 |
66 |
67 |
68 |
69 |
--------------------------------------------------------------------------------
/src/main/java/net/aimeizi/spring/data/elasticsearch/example/Author.java:
--------------------------------------------------------------------------------
1 | package net.aimeizi.spring.data.elasticsearch.example;
2 |
3 | public class Author {
4 |
5 | private String id;
6 | private String name;
7 |
8 | public Author() {
9 | }
10 |
11 | public Author(String id, String name) {
12 | super();
13 | this.id = id;
14 | this.name = name;
15 | }
16 |
17 | public String getId() {
18 | return id;
19 | }
20 |
21 | public void setId(String id) {
22 | this.id = id;
23 | }
24 |
25 | public String getName() {
26 | return name;
27 | }
28 |
29 | public void setName(String name) {
30 | this.name = name;
31 | }
32 |
33 | @Override
34 | public String toString() {
35 | return "Author [id=" + id + ", name=" + name + "]";
36 | }
37 |
38 |
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/net/aimeizi/spring/data/elasticsearch/example/Book.java:
--------------------------------------------------------------------------------
1 | package net.aimeizi.spring.data.elasticsearch.example;
2 |
3 | import org.springframework.data.annotation.Id;
4 | import org.springframework.data.elasticsearch.annotations.Document;
5 | import org.springframework.data.elasticsearch.annotations.Field;
6 | import org.springframework.data.elasticsearch.annotations.FieldIndex;
7 | import org.springframework.data.elasticsearch.annotations.FieldType;
8 |
9 |
10 | @Document(indexName= "book", type= "book", indexStoreType = /*"fs"*/"memory", shards = 1, replicas = 0, refreshInterval = "-1")
11 | public class Book{
12 |
13 | @Id
14 | private Integer id;
15 | private String name;
16 | private String desc;
17 | @Field(index=FieldIndex.not_analyzed)
18 | private String url;
19 | @Field(index=FieldIndex.not_analyzed)
20 | private String pubdate;
21 | private String pubinfo;
22 | @Field(type=FieldType.Nested)
23 | private Author author;
24 | @Field(type=FieldType.Float,index=FieldIndex.not_analyzed)
25 | private Double price;
26 |
27 | public Book() {
28 |
29 | }
30 |
31 | public Book(Integer id, String name, String desc, String url, String pubdate,
32 | String pubinfo, Author author, Double price) {
33 | super();
34 | this.id = id;
35 | this.name = name;
36 | this.desc = desc;
37 | this.url = url;
38 | this.pubdate = pubdate;
39 | this.pubinfo = pubinfo;
40 | this.author = author;
41 | this.price = price;
42 | }
43 |
44 |
45 |
46 | public Integer getId() {
47 | return id;
48 | }
49 | public void setId(Integer id) {
50 | this.id = id;
51 | }
52 | public String getName() {
53 | return name;
54 | }
55 | public void setName(String name) {
56 | this.name = name;
57 | }
58 |
59 | public String getDesc() {
60 | return desc;
61 | }
62 |
63 | public void setDesc(String desc) {
64 | this.desc = desc;
65 | }
66 |
67 | public String getUrl() {
68 | return url;
69 | }
70 | public void setUrl(String url) {
71 | this.url = url;
72 | }
73 | public String getPubdate() {
74 | return pubdate;
75 | }
76 | public void setPubdate(String pubdate) {
77 | this.pubdate = pubdate;
78 | }
79 |
80 | public String getPubinfo() {
81 | return pubinfo;
82 | }
83 |
84 | public void setPubinfo(String pubinfo) {
85 | this.pubinfo = pubinfo;
86 | }
87 |
88 | public Author getAuthor() {
89 | return author;
90 | }
91 | public void setAuthor(Author author) {
92 | this.author = author;
93 | }
94 |
95 | public Double getPrice() {
96 | return price;
97 | }
98 |
99 | public void setPrice(Double price) {
100 | this.price = price;
101 | }
102 |
103 | @Override
104 | public String toString() {
105 | return "Book [id=" + id + ", name=" + name + ", desc=" + desc
106 | + ", url=" + url + ", pubdate=" + pubdate + ", pubinfo="
107 | + pubinfo + ", author=" + author + ", price=" + price + "]";
108 | }
109 |
110 |
111 |
112 | }
113 |
--------------------------------------------------------------------------------
/src/main/java/net/aimeizi/spring/data/elasticsearch/example/repository/BookRepository.java:
--------------------------------------------------------------------------------
1 | package net.aimeizi.spring.data.elasticsearch.example.repository;
2 |
3 | import java.util.List;
4 |
5 | import net.aimeizi.spring.data.elasticsearch.example.Book;
6 |
7 | import org.springframework.data.domain.Page;
8 | import org.springframework.data.domain.Pageable;
9 | import org.springframework.data.elasticsearch.annotations.Query;
10 | import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
11 | import org.springframework.stereotype.Repository;
12 |
13 | @Repository
14 | public interface BookRepository extends ElasticsearchRepository{
15 |
16 | List findByNameAndPrice(String name, Float price);
17 |
18 | List findByNameOrPrice(String name, Float price);
19 |
20 | Page findByName(String name,Pageable page);
21 |
22 | Page findByNameNot(String name,Pageable page);
23 |
24 | Page findByPriceBetween(Float price,Pageable page);
25 |
26 | Page findByNameLike(String name,Pageable page);
27 |
28 | @Query("{\"bool\" : {\"must\" : {\"term\" : {\"price\" : \"?0\"}}}}")
29 | Page findByPrice(Float price, Pageable pageable);
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/net/aimeizi/spring/data/elasticsearch/example/service/BookService.java:
--------------------------------------------------------------------------------
1 | package net.aimeizi.spring.data.elasticsearch.example.service;
2 |
3 | import java.util.List;
4 |
5 | import net.aimeizi.spring.data.elasticsearch.example.Book;
6 |
7 | import org.springframework.data.domain.Page;
8 | import org.springframework.data.domain.Pageable;
9 | import org.springframework.stereotype.Service;
10 |
11 | @Service
12 | public interface BookService {
13 |
14 | List findByNameAndPrice(String name, Float price);
15 |
16 | List findByNameOrPrice(String name, Float price);
17 |
18 | Page findByName(String name,Pageable page);
19 |
20 | Page findByNameNot(String name,Pageable page);
21 |
22 | Page findByPriceBetween(Float price,Pageable page);
23 |
24 | Page findByNameLike(String name,Pageable page);
25 |
26 | Page findByPrice(Float price, Pageable pageable);
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/net/aimeizi/spring/data/elasticsearch/example/service/impl/BookServiceImpl.java:
--------------------------------------------------------------------------------
1 | package net.aimeizi.spring.data.elasticsearch.example.service.impl;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.data.domain.Page;
7 | import org.springframework.data.domain.Pageable;
8 |
9 | import net.aimeizi.spring.data.elasticsearch.example.Book;
10 | import net.aimeizi.spring.data.elasticsearch.example.repository.BookRepository;
11 | import net.aimeizi.spring.data.elasticsearch.example.service.BookService;
12 |
13 | public class BookServiceImpl implements BookService{
14 |
15 | @Autowired
16 | private BookRepository bookRepository;
17 |
18 | @Override
19 | public List findByNameAndPrice(String name, Float price) {
20 | return bookRepository.findByNameAndPrice(name, price);
21 | }
22 |
23 | @Override
24 | public List findByNameOrPrice(String name, Float price) {
25 | return bookRepository.findByNameOrPrice(name, price);
26 | }
27 |
28 | @Override
29 | public Page findByName(String name, Pageable page) {
30 | return bookRepository.findByName(name, page);
31 | }
32 |
33 | @Override
34 | public Page findByNameNot(String name, Pageable page) {
35 | return bookRepository.findByNameNot(name, page);
36 | }
37 |
38 | @Override
39 | public Page findByPriceBetween(Float price, Pageable page) {
40 | return bookRepository.findByPriceBetween(price, page);
41 | }
42 |
43 | @Override
44 | public Page findByNameLike(String name, Pageable page) {
45 | return bookRepository.findByNameLike(name, page);
46 | }
47 |
48 | @Override
49 | public Page findByPrice(Float price, Pageable pageable) {
50 | return bookRepository.findByPrice(price, pageable);
51 | }
52 |
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/src/main/resources/applicationContext.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
10 |
11 |
13 |
14 |
15 |
16 |
18 |
--------------------------------------------------------------------------------
/src/main/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | %d %5p %40.40c:%4L - %m%n
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/src/main/webapp/WEB-INF/web.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | spring-data-elasticsearch-example
4 |
5 |
6 | 30
7 |
8 |
9 |
10 | index.jsp
11 |
12 |
13 |
--------------------------------------------------------------------------------
/src/test/java/net/aimeizi/spring/data/elasticsearch/example/repository/test/BookRepositoryTest.java:
--------------------------------------------------------------------------------
1 | package net.aimeizi.spring.data.elasticsearch.example.repository.test;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.Iterator;
6 | import java.util.List;
7 | import java.util.Map;
8 |
9 | import net.aimeizi.spring.data.elasticsearch.example.Author;
10 | import net.aimeizi.spring.data.elasticsearch.example.Book;
11 | import net.aimeizi.spring.data.elasticsearch.example.repository.BookRepository;
12 |
13 | import org.elasticsearch.action.search.SearchResponse;
14 | import org.elasticsearch.action.suggest.SuggestResponse;
15 | import org.elasticsearch.index.query.QueryBuilder;
16 | import org.elasticsearch.index.query.QueryBuilders;
17 | import org.elasticsearch.index.query.TermQueryBuilder;
18 | import org.elasticsearch.search.SearchHit;
19 | import org.elasticsearch.search.highlight.HighlightBuilder;
20 | import org.elasticsearch.search.highlight.HighlightField;
21 | import org.elasticsearch.search.suggest.Suggest;
22 | import org.elasticsearch.search.suggest.Suggest.Suggestion;
23 | import org.elasticsearch.search.suggest.Suggest.Suggestion.Entry;
24 | import org.elasticsearch.search.suggest.Suggest.Suggestion.Entry.Option;
25 | import org.elasticsearch.search.suggest.SuggestBuilder.SuggestionBuilder;
26 | import org.elasticsearch.search.suggest.term.TermSuggestionBuilder;
27 | import org.junit.Before;
28 | import org.junit.Test;
29 | import org.junit.runner.RunWith;
30 | import org.springframework.beans.factory.annotation.Autowired;
31 | import org.springframework.data.domain.Page;
32 | import org.springframework.data.domain.PageRequest;
33 | import org.springframework.data.domain.Pageable;
34 | import org.springframework.data.domain.Sort;
35 | import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
36 | import org.springframework.data.elasticsearch.core.FacetedPage;
37 | import org.springframework.data.elasticsearch.core.FacetedPageImpl;
38 | import org.springframework.data.elasticsearch.core.SearchResultMapper;
39 | import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
40 | import org.springframework.data.elasticsearch.core.query.SearchQuery;
41 | import org.springframework.test.context.ContextConfiguration;
42 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
43 |
44 | /**
45 | * 详情参考:https://github.com/BioMedCentralLtd/spring-data-elasticsearch-sample-application
46 | * @author Administrator
47 | *
48 | */
49 | @RunWith(SpringJUnit4ClassRunner.class)
50 | @ContextConfiguration("classpath:applicationContext.xml")
51 | public class BookRepositoryTest{
52 |
53 | @Autowired
54 | private BookRepository repository;
55 |
56 | @Autowired
57 | private ElasticsearchTemplate elasticsearchTemplate;
58 |
59 | @Before
60 | public void before() {
61 | elasticsearchTemplate.deleteIndex(Book.class);
62 | elasticsearchTemplate.createIndex(Book.class);
63 | initIndex();
64 | elasticsearchTemplate.refresh(Book.class, true);
65 | }
66 |
67 | /**
68 | * 初始化索引
69 | */
70 | public void initIndex(){
71 | Book book1 = new Book();
72 | book1.setId(1);
73 | book1.setName("云去云来");
74 | book1.setDesc("水深水浅,云去云来,听林青霞的第一本有声书。林青霞说:宋代词人蒋捷的《听雨》,这何尝不是我内心的写照。“少年听雨歌楼上,红烛昏罗帐”,那些年在台湾拍戏拍得火红火绿的。“壮年听雨客舟中,江阔云低,断雁叫西风”,而立之年,孤身在香港拍戏,一待就是十年,曾经试过,独自守着窗儿,对着美丽绚烂的夜景,寂寞得哭泣。“而今听雨僧庐下,鬓已星星也。悲欢离合总无情,一任阶前,点滴到天明。”而今真是鬓已星星也,到了耳顺之年,历尽人生的甜酸苦辣、生离死别,接受了这些人生必经的过程,心境渐能平和,如今能够看本好书,与朋友交换写作心得,已然满足。人生很难有两个甲子,我唯一一个甲子的岁月出了第二本书《云去云来》,当是给自己的一份礼物,也好跟大家分享我这一甲子的人、事、情");
75 | book1.setAuthor(new Author("1","林青霞"));
76 | book1.setUrl("http://book.douban.com/subject/26133987/");
77 | book1.setPubinfo("广西师范大学出版社");
78 | book1.setPubdate("2014-11");
79 | book1.setPrice(79.00);
80 |
81 |
82 | Book book2 = new Book();
83 | book2.setId(2);
84 | book2.setName("这些人,那些事");
85 | book2.setDesc("吴念真累积多年、珍藏心底的体会与感动。他写的每个故事,都蕴藏了我们无法预知的生命能量与心灵启发。跟他一起回望人生种种,您将学会包容、豁达与感恩……本书是吴念真导演经历过人生的风风雨雨和最大低潮后,所完成的生命记事。他用文字写下心底最挂念的家人、日夜惦记的家乡、一辈子搏真情的朋友,以及台湾各个角落里最真实的感动。这些人和事,透过他真情挚意的笔,如此跃然的活在你我眼前,笑泪交织的同时,也无可取代的成为烙印在你我心底、这一个时代的美好缩影……特别收录 吴念真近年唯一小说创作《遗书》,写下对胞弟离开人间的真情告白特别邀请 作家雷骧绘制插画,看两位大师以图文激荡出精采火花生命里某些当时充满怨怼的曲折,在后来好像都成了一种能量和养分……这些人、那些事在经过时间的筛滤之后,几乎都只剩下笑与泪与感动和温暖。——《这些人,那些事》");
86 | book2.setAuthor(new Author("2","吴念真"));
87 | book2.setUrl("http://book.douban.com/subject/6388661/");
88 | book2.setPubinfo("译林出版社");
89 | book2.setPubdate("2011-9");
90 | book2.setPrice(28.00);
91 |
92 | Book book3 = new Book();
93 | book3.setId(3);
94 | book3.setName("我们为什么会分手");
95 | book3.setDesc("“我们似乎热恋过,但我们似乎从未彼此了解。”任何一次分手,留下的都不该只是伤痛,或是对爱情的怀疑,也可以是一次成长。遭遇过分手的人都会问:“我们为什么会分手?”而恰恰正是经历同一段感情的 两个人,会给出不同的答案。分手是如此微妙,让作者毛路和赵珈禾萌生了采访分手情侣的想法。她们在网络上征集,愿意单方面讲述的人众多,双方都愿意的则寥寥无几。在三年多的坚持下,最终采访到22对分手恋人。本书会与您分享其中15对的故事。在男女双方分别回顾恋爱过程、讲述各自心中真实的分手理由时,你会惊讶地发现,性别视角和思维方式上的差异,竟让同一段");
96 | book3.setAuthor(new Author("3","毛路"));
97 | book3.setUrl("http://book.douban.com/subject/26146992/");
98 | book3.setPubinfo("北京联合出版公司");
99 | book3.setPubdate("2014-11-1");
100 | book3.setPrice(32.00);
101 |
102 | Book book4 = new Book();
103 | book4.setId(4);
104 | book4.setName("挪威的森林");
105 | book4.setDesc("这是一部动人心弦的、平缓舒雅的、略带感伤的恋爱小说。小说主人公渡边以第一人称展开他同两个女孩间的爱情纠葛。渡边的第一个恋人直子原是他高中要好同学木月的女友,后来木月自杀了。一年后渡边同直子不期而遇并开始交往。此时的直子已变得娴静腼腆,美丽晶莹的眸子里不时掠过一丝难以捕捉的阴翳。两人只是日复一日地在落叶飘零的东京街头漫无目标地或前或后或并肩行走不止。直子20岁生日的晚上两人发生了性关系,不料第二天直子便不知去向。几个月后直子来信说她住进一家远在深山里的精神疗养院。渡边前去探望时发现直子开始带有成熟女性的丰腴与娇美。晚间两人虽同处一室,但渡边约束了自己,分手前表示永远等待直子。返校不久,由于一次偶然相遇,渡边开始与低年级的绿子交往。绿子同内向的直子截然相反,“简直就像迎着春天的晨光蹦跳到世界上来的一头小鹿”。这期间,渡边内心十分苦闷彷徨。一方面念念不忘直");
106 | book4.setAuthor(new Author("4","村上春树 "));
107 | book4.setUrl("http://book.douban.com/subject/2159042/");
108 | book4.setPubinfo("上海译文出版社");
109 | book4.setPubdate("2007-7");
110 | book4.setPrice(23.00);
111 |
112 | Book book5 = new Book();
113 | book5.setId(5);
114 | book5.setName("盗墓笔记2");
115 | book5.setDesc("朋友老痒出狱,给刚从西礁海底墓归来、在家赋闲没有几日的主人公——“我”带来一个惊人的消息:诡异的六角铃铛,古老的厍族,巨大的青铜树,遥远的秦岭腹地……“我”不由得跃跃欲试。接下来,“我”和老痒二人孤身深入到神秘莫测的秦岭探险。但前方等待着他们的又是什么?——各种诡异事物接踵而来,哲罗鲑,黄泉瀑布,尸阵,麒麟竭,烛九阴……这棵巨大的青铜树究竟是做什么用的?是一棵许愿树,还是一个少数民族的图腾?他们到底能不能找到真正的答案?探险的过程充满了人性的挣扎和努力,可怖的人物与可憎的面孔交织出现。最后,是一个让人瞠目结舌,超乎所有想象都无法猜透,却又似乎真实可信的结局");
116 | book5.setAuthor(new Author("5","南派三叔"));
117 | book5.setUrl("http://book.douban.com/subject/2057285/");
118 | book5.setPubinfo("中国友谊出版公司");
119 | book5.setPubdate("2007-4");
120 | book5.setPrice(26.80);
121 |
122 | repository.save(Arrays.asList(book1, book2, book3, book4, book5));
123 | }
124 |
125 | @Test
126 | public void doBulkIndexDocument() {
127 |
128 | Book book1 = repository.findOne(1);
129 | print(book1);
130 | Book book2 = repository.findOne(2);
131 | print(book2);
132 | Book book3 = repository.findOne(3);
133 | print(book3);
134 | Book book4 = repository.findOne(4);
135 | print(book4);
136 | Book book5 = repository.findOne(5);
137 | print(book5);
138 |
139 | }
140 |
141 | @Test
142 | public void findByNameAndPrice(){
143 | initIndex();
144 | List list = repository.findByNameAndPrice("挪威的森林", 23.00f);
145 | for (Book book : list) {
146 | print(book);
147 | }
148 | }
149 |
150 | @Test
151 | public void findByPrice(){
152 | initIndex();
153 | Page page = repository.findByPrice(23.00f, new PageRequest(0, 20));
154 | for (Book book : page.getContent()) {
155 | print(book);
156 | }
157 | }
158 |
159 | @Test
160 | public void deleteBook(){
161 | initIndex();
162 | repository.delete(2);
163 | Book book = repository.findOne(2);
164 | print(book);
165 | }
166 |
167 | @Test
168 | public void findAllBooks(){
169 | initIndex();
170 | Iterable all = repository.findAll();
171 | Iterator iterator = all.iterator();
172 | while (iterator.hasNext()) {
173 | Book book = (Book) iterator.next();
174 | print(book);
175 | }
176 | }
177 |
178 |
179 | @Test
180 | public void deleteAllBooks(){
181 | initIndex();
182 | repository.deleteAll();
183 | Iterable all = repository.findAll();
184 | Iterator iterator = all.iterator();
185 | while (iterator.hasNext()) {
186 | Book book = (Book) iterator.next();
187 | print(book);
188 | }
189 | elasticsearchTemplate.deleteIndex(Book.class);//删除索引目录
190 | }
191 |
192 |
193 | @Test
194 | public void sortByPrice(){
195 | initIndex();
196 | Iterable all = repository.findAll(new Sort(new Sort.Order(Sort.Direction.DESC,"price")));
197 | Iterator iterator = all.iterator();
198 | while (iterator.hasNext()) {
199 | Book book = (Book) iterator.next();
200 | print(book);
201 | }
202 | elasticsearchTemplate.deleteIndex(Book.class);//删除索引目录
203 | }
204 |
205 | @Test
206 | public void queryTearm(){
207 | initIndex();
208 | TermQueryBuilder termQuery = QueryBuilders.termQuery("desc", "内心");
209 | Iterator iterator = repository.search(termQuery).iterator();
210 | while (iterator.hasNext()) {
211 | Book book = (Book) iterator.next();
212 | print(book);
213 | }
214 | elasticsearchTemplate.deleteIndex(Book.class);//删除索引目录
215 | }
216 |
217 |
218 | @Test
219 | public void count(){
220 | initIndex();
221 | long count = repository.count();
222 | System.out.println(count);
223 | }
224 |
225 |
226 | @Test
227 | public void isExists(){
228 | initIndex();
229 | boolean exists = repository.exists(2);
230 | System.out.println(exists);
231 | }
232 |
233 | /**
234 | * 高亮查询
235 | */
236 | @Test
237 | public void searchQuery(){
238 | initIndex();
239 | QueryBuilder queryBuilder = QueryBuilders.queryString("内心");
240 | SearchQuery searchQuery = new NativeSearchQueryBuilder()
241 | .withQuery(queryBuilder)
242 | .withHighlightFields(new HighlightBuilder.Field("name").preTags("").postTags("").fragmentSize(250))
243 | .withHighlightFields(new HighlightBuilder.Field("desc").preTags("").postTags("").fragmentSize(250))
244 | .withPageable(new PageRequest(0, 20))
245 | .build();
246 | Page queryForPage = elasticsearchTemplate.queryForPage(searchQuery, Book.class, new SearchResultMapper() {
247 |
248 | @SuppressWarnings("unchecked")
249 | @Override
250 | public FacetedPage mapResults(SearchResponse response,
251 | Class clazz, Pageable pageable) {
252 | System.out.println("本次查询共耗时:"+response.getTookInMillis()+"毫秒.");
253 | List books = new ArrayList();
254 | for(SearchHit searchHit : response.getHits()){
255 | if (response.getHits().getHits().length <= 0) {
256 | return null;
257 | }
258 | Book book = new Book();
259 | Map source = searchHit.getSource();
260 | book.setId((Integer)source.get("id"));
261 | book.setPrice((Double)source.get("price"));
262 | Map highlightFields = searchHit.getHighlightFields();
263 | HighlightField highlightNameField = highlightFields.get("name");
264 | if(highlightNameField!=null&&highlightNameField.fragments()!=null){
265 | book.setName(highlightNameField.fragments()[0].string());
266 | }else{
267 | book.setName((String)source.get("name"));
268 | }
269 | HighlightField highlightDescField = highlightFields.get("desc");
270 | if(highlightDescField!=null&&highlightDescField.fragments()!=null){
271 | book.setDesc(highlightDescField.fragments()[0].string());
272 | }else{
273 | book.setDesc((String)source.get("desc"));
274 | }
275 | Map map = (Map) source.get("author");
276 | Author author = new Author();
277 | author.setId((String)map.get("id"));
278 | author.setName((String)map.get("name"));
279 | book.setAuthor(author);
280 | book.setUrl((String)source.get("url"));
281 | book.setPubinfo((String)source.get("pubinfo"));
282 | book.setPubdate((String)source.get("pubdate"));
283 | books.add(book);
284 | }
285 | if (books.size() > 0) {
286 | return new FacetedPageImpl((List) books);
287 | }
288 | return null;
289 | }
290 |
291 | });
292 | System.out.println("总页数:"+queryForPage.getTotalPages());
293 | System.out.println("总记录数:"+queryForPage.getTotalElements());
294 | List content = queryForPage.getContent();
295 | for (Book book : content) {
296 | print(book);
297 | }
298 | elasticsearchTemplate.deleteIndex(Book.class);//删除索引目录
299 | }
300 |
301 | @Test
302 | public void suggest(){
303 | // SuggestionBuilder> suggestionBuilder = new TermSuggestionBuilder("mySuggestion");
304 | // suggestionBuilder.text("内心 消息 民族 性虐 优乐美 聚划算 德芙 加多宝 好声音");
305 | // suggestionBuilder.size(20);
306 | // SuggestResponse suggestResponse = elasticsearchTemplate.suggest(suggestionBuilder, Book.class);
307 | // Suggest suggest = suggestResponse.getSuggest();
308 | // Suggestion extends Entry extends Option>> suggestion = suggest.getSuggestion("mySuggestion");
309 | // List extends Entry extends Option>> entries = suggestion.getEntries();
310 | // for (Entry extends Option> entry : entries) {
311 | // System.out.println(entry.getText().string());
312 | // }
313 | }
314 |
315 | private void print(Book book) {
316 | System.out.println("----------------------------");
317 | System.out.println(book);
318 | }
319 |
320 |
321 | }
322 |
--------------------------------------------------------------------------------