实例使用IntelliJ IDEA开发SpringBoot项目,并在项目中集成ElasticSearch(简称ES), 通过jest来连接ES, 在ES中创建索引, 类型和文档及相应的属性数据, 还可以通过jest来查询ES中存储的数据 (通过构建复杂的查询语句可以实现功能强大的文本搜索)
项目对应的实例代码可以通过【下载实例】按钮获取
开发工具: IntelliJ IDEA, JDK1.8, Maven3.0.2, ElasticSearch-5.6.7(windows版), Fiddler4 (http工具)
【项目包含内容】(见下图):

1. 将工程导入IntelliJ IDEA

2. 下载并解压 ElasticSearch-5.6.7, 打开安装目录 bin下面 elasticsearch.bat
注意: 启动ES前要保证电脑已经安装了 JDK1.8

3. 如果es正常启动, 在地址栏中访问 http://localhost:9200/, 能访问下图说明启动成功

4. 在IntelliJ中配置 访问ES的jar包jest, 注意 由于 es的版本是5.x, 对应的jest也要是5.x, 否则会出现兼容性问题
<dependency> <groupId>io.searchbox</groupId> <artifactId>jest</artifactId> <version>5.3.4</version> </dependency>
5. 添加测试类
注意: 切记 索引值不要出现大写字母, 切记 类型值不要出现大写字母
@RunWith(SpringRunner.class)
@SpringBootTest
public class ElasticApplicationTests {
@Autowired
JestClient jestClient;
@Test
public void contextLoads() {
Article article = new Article();
article.setId(1);
article.setTitle("aa");
article.setAuthor("bb");
article.setContent("Hello World!");
//构建一个索引 索引: Library 类型: books 貌似不能大写
Index index = new Index.Builder(article).index("mylibrary").type("mybook").build();
try {
jestClient.execute(index);
} catch (IOException e) {
e.printStackTrace();
}
}
//测试搜索
@Test
public void search(){
String strJson = "{\n" +
"\t\"query\":{\n" +
"\t\t\"match\":{\n" +
"\t\t\t\"content\":\"hello\"\n" +
"\t\t}\n" +
"\t}\n" +
"}";
Search search = new Search.Builder(strJson).addIndex("mylibrary").addType("mybook").build();
try {
SearchResult searchResult = jestClient.execute(search);
System.out.println(searchResult.getJsonString());
} catch (IOException e) {
e.printStackTrace();
}
}
}6. 通过http工具操作es

1. 向es添加内容
使用put将json串的内容添加到es中
put http://localhost:9200/library/book/1
{
"first_name" : "ge panjiang1",
"last_name" : "ok",
"age" : 25,
"about" : "I love to go rock climbing",
"interests" : ["sports", "music"]
}
索引类比于 关系型数据库名称
类型类比于 关系型数据库表名
2. 查询es中的内容
GET http://localhost:9200/library/book/1


3. 删除es中的内容
DELETE http://localhost:9200/library/book/1
下载Demo