相关jar包的maven如下:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.2.2</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>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
如果使用的是springboot,默认的elasticsearch的版本是2.4.6,亲测有bug,建议使用5.2.2.需要修改版本
<properties>
<elasticsearch.version>5.2.2</elasticsearch.version>
</properties>
下面开始测试
首先写了个工具类来获取客户端对象
public Client getClient(){
TransportClient client=null;
try {
Settings settings = Settings.builder()
.put("client.transport.sniff", true).build();
client = new PreBuiltTransportClient(settings);
//添加地址到client中
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
} catch (UnknownHostException e) {
e.printStackTrace();
}
return client;
}
接下来查询员工数据并创建索引
@Test
public void testCreateEmployeeIndexToES() throws Exception {
Client client = getClient();
List<Employee> list = employeeService.selectAll();
for (Employee employee : list) {
String empJson = JSON.toJSONString(employee);
client.prepareIndex("test", "employee", employee.getId().toString())
.setSource(empJson).get();
}
}
测试成功后进入kibana5服务管理平台
创建索引成功!
接下来测试模糊查询
@Test
public void testWildcardQuery() throws Exception {
Client client = getClient();
WildcardQueryBuilder usernames = new WildcardQueryBuilder("username", "asd*");
SearchResponse searchResponse = client.prepareSearch("test").setQuery(usernames).addSort("id", SortOrder.ASC).get();
SearchHit[] hits = searchResponse.getHits().getHits();
System.out.println("总条数:"+hits.length);
for (SearchHit searchHit : hits) {
Map<String, Object> source = searchHit.getSource();
String empStr = JSON.toJSONString(source);
Employee employee = JSON.parseObject(empStr, Employee.class);
System.out.println(employee);
}
}
测试结果如下
要点总结:
创建索引需要把Employee对象转换成json字符串
而查询则需要将json字符串转换成Employee对象