ElasticSearch6.x 基于SpringBoot 实现ElasticSearch的文档管理
前景提要:
ElasticSearch6.x 搜索引擎服务支持四种方式导入文档对象:
1、byte[]:字节数组(JSON格式文档手动转换为 byte[]或String)
2、Map:键值对(使用Map,代表一个JSON文档)
3、实体对象:JavaBean(使用Jackson 等第三方库把JavaBean转换为JSON)
4、内置帮助类XContentFactory(使用内置帮助类XContentFactory的.jsonBuilder()方法)
SpringBoot 功能封装涉及ElasticSearch的文档管理方法约定如下:
createJACKSONDocument(String index, String type, byte[] bytes):新建文档,基于byte[]
createJSONDocument(String index, String type, String json):新建文档,基于json
createMapDocument(String index, String type, Map map):新建文档,基于map
createXContentBuilderDocument(String index, String type, XContentBuilder builder):新建文档,基于XContentBuilder
在上一篇文中说到:ElasticSearch6.x 基于SpringBoot 实现ElasticSearch连接功能封装,将约定的方法填充到ElasticSearchIndexUtil.java 工具类中。
@Component
public class ElasticSearchIndexUtil {
// 引入 Ela 连接实列化对象
@Autowired
private TransportClient client;
/**
* 功能描述:创建文档
*
* @param index
* 索引名
* @param type
* 类型
* @param map
* 文档数据源
*/
public Result createMapDocument(String index, String type, Map map) {
IndexResponse response = client.prepareIndex(index, type).setSource(map).get();
return response.getResult();
}
/**
* 功能描述:创建文档
*
* @param index
* 索引名
* @param type
* 类型
* @param json
* 文档数据源
*/
public Result createJSONDocument(String index, String type, String json) {
IndexResponse response = client.prepareIndex(index, type).setSource(json).get();
return response.getResult();
}
/**
* 功能描述:创建文档
*
* @param index
* 索引名
* @param type
* 类型
* @param bytes
* 文档数据源
*/
public Result createJACKSONDocument(String index, String type, byte[] bytes) {
IndexResponse response = client.prepareIndex(index, type).setSource(bytes).get();
return response.getResult();
}
/**
* 功能描述:创建文档
*
* @param index
* 索引名
* @param type
* 类型
* @param source
* 文档数据源
*/
public Result createXContentBuilderDocument(String index, String type, XContentBuilder builder) {
IndexResponse response = client.prepareIndex(index, type).setSource(builder).get();
return response.getResult();
}
}
编写测试工具类Test.java ,测试相关封装的功能代码:
@RunWith(SpringRunner.class)
@SpringBootTest
// 由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。
@WebAppConfiguration
public class Test {
@Autowired
private ElasticSearchIndexUtil util;
@org.junit.Test
public void createMapDocument() {
Map<String, Object> source = new HashMap<String, Object>();
source.put("user", "zzg");
source.put("postDate", "2019-07-18");
source.put("message", "trying out Elasticsearch");
util.createMapDocument("book", "library", source);
}
/**其他索引功能方法请自行测试**/
}
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。