使用Java简单操作Elasticsearch

Posted by 石玉军 on 2018-07-26

1.添加maven依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.5.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch-transport-wares</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.5.2</version>
<scope>compile</scope>
</dependency>

2.创建连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Configuration
public class ElasticsearchConfig {

@Bean
public TransportClient client() throws UnknownHostException {
Settings esSetting = Settings.builder()
.put("thread_pool.search.size", 3)
.build();
InetSocketTransportAddress node1 = new InetSocketTransportAddress(InetAddress.getByName("服务器地址"),
9300
);

TransportClient client = new PreBuiltTransportClient(esSetting);
client.addTransportAddress(node1);
return client;
}
}

因为我是使用的SpringBoot所以使用此种方式创建bean,使用别的框架的同学请自行切换

3.使用
在进行使用之前,先说一下Elasticsearch中的几个简单的概念。

索引:在Elasticsearch中可以简单把索引理解为数据库名称。
type:在Elasticsearch中可以简单把type理解为表名称。
1.添加数据

1
2
3
4
5
6
7
@Autowired
TransportClient transportClient;
public void insertBlog(Blog blog) throws Exception {
JsonObject jsonObject = JsonObjectTool.object2JsonObject(blog);
transportClient.prepareIndex("blog", "Test", blog.getId())
.setSource(jsonObject.toString(), XContentType.JSON).get();
}

此方法就是保存博客的方法了,我将博客对象转为一个Json对象,然后保存在了索引为blog、type为Test中的一个文档中,我指定了他的id为blogs对象的id。

2.更新数据

1
2
3
4
5
6
public void updateBlog(Blog blog) throws Exception {
JsonObject jsonObject = JsonObjectTool.object2JsonObject(blog);
transportClient.prepareUpdate("blog", "Test",, blog.getId())
.setDoc(jsonObject.toString(), XContentType.JSON).get();

}

3.删除数据

1
2
3
public void deleteBlog(String id) throws Exception {
transportClient.prepareDelete("blog", "Test", id).get();
}

4.根据id获取信息

1
2
3
4
public Blog selectOneBlog(String id) throws Exception {
GetResponse getResponse = transportClient.prepareGet("blog", "Test", id).get();
return JsonObjectTool.jsonObject2Object(JsonObjectTool.string2JsonObject(getResponse.getSourceAsString()), Blog.class);
}

5.复杂多条件查询
敲黑板了,咳咳,最重要的部分来了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
public PageInfo<Blog> selectBlogsList(int from, int size, String serch, Map map) throws Exception {
from = (from - 1) * size;//因为el的搜索分页功能是算的从第几条开始而不是从第几页开始,所以我们把开始页数通过计算转为开始条数
SearchResponse response;//查询返回结果集
SearchRequestBuilder srb = transportClient.prepareSearch("blog").setTypes("Test");
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
if (!map.isEmpty()) {//这个map呢,封装的是必须的查询条件,比如说我要查审核通过的博客或者说是草稿状态的博客。
Set<String> set = map.keySet();
for (String key : set) {
QueryBuilder query = QueryBuilders.matchPhraseQuery(key, map.get(key));
boolQueryBuilder.must(query);//mast就代表这个条件必须符合
}
}
if (serch != null && serch != "") {//这个serch呢,存放的是查询的关键字。
QueryBuilder queryBlogsName = QueryBuilders.matchPhraseQuery("blogsName", serch);
QueryBuilder queryBlogsClassifyName = QueryBuilders.matchPhraseQuery("blogsClassifyName", serch);
QueryBuilder queryBlogsPart = QueryBuilders.matchPhraseQuery("blogsPart", serch);
QueryBuilder queryUserName = QueryBuilders.matchPhraseQuery("userName", serch);
response = srb.setQuery(QueryBuilders.boolQuery()
.should(queryUserName)//should表示不是必须符合,但是如果符合的话会加分,分值越高查询出来位置越前
.should(queryBlogsName)
.should(queryBlogsClassifyName)
.should(queryBlogsPart))
.setFetchSource(null, "blogsUrl")//查询时过滤掉此字段,不会查询出来
.setFrom(from)//从第几条开始
.setSize(size)//查询几条
.addSort("createdTime", SortOrder.DESC)//根据createdTime降序
.setTimeout(new TimeValue(5, TimeUnit.SECONDS))//等待5秒后不管查询是否完成强制返回结果
.execute()
.actionGet();
} else {
response = srb.setQuery(boolQueryBuilder)
.setFrom(from)
.setSize(size)
.addSort("createdTime", SortOrder.DESC)
.setFetchSource(null, "blogsUrl")
.setTimeout(new TimeValue(5, TimeUnit.SECONDS))
.execute()
.actionGet();
}
SearchHits hits = response.getHits();//hits存放的就是返回的查询结果list
List<Blogs> list = new ArrayList<>();


Blog blog;
StringBuffer sb = new StringBuffer();
for (SearchHit hit : hits) {
sb.append(hit.getSourceAsString());//每条记录都是以字符串存放的
if (serch != null && serch != "") {
blog = JsonObjectTool.jsonObject2Object(JsonObjectTool.string2JsonObject(sb.toString().replaceAll(serch, "<strong style='color:red;'>" + serch + "</strong>")), Blog.class);//对查询关键字进行标红
} else {
blog = JsonObjectTool.jsonObject2Object(JsonObjectTool.string2JsonObject(sb.toString()), Blog.class);
}
blog.setId(hit.getId());
list.add(blog);
sb.delete(0, sb.length());
}
PageInfo<Blog> pageInfo = new PageInfo<>(list);
pageInfo.setTotal(response.getHits().getTotalHits());//数据总条数
return pageInfo;
}