全网最详细的大数据ELK文章系列,强烈建议收藏加关注!
新文章都已经列出历史文章目录,帮助大家回顾前面的知识重点。
目录
Elasticsearch编程
一、添加职位数据
1、初始化客户端连接
2、实现关闭客户端连接
3、编写代码实现新增职位数据
4、编写测试用例测试添加方法
参考代码:
private RestHighLevelClient restHighLevelClient; private static final String JOB_IDX_NAME = "job_idx"; public JobFullTextServiceImpl() { restHighLevelClient = new RestHighLevelClient(RestClient.builder( new HttpHost("node1", 9200, "http") , new HttpHost("node2", 9200, "http") , new HttpHost("node3", 9200, "http") )); }
@Override public void close() { try { restHighLevelClient.close(); } catch (IOException e) { e.printStackTrace(); } }
实现步骤:
参考代码:
@Override public void add(JobDetail jobDetail) { // 1. 构建IndexRequest对象,用来描述ES发起请求的数据。 IndexRequest indexRequest = new IndexRequest(JOB_IDX_NAME); // 2. 设置文档ID。 indexRequest.id(jobDetail.getId() + ""); // 3. 构建一个实体类对象,并使用FastJSON将实体类对象转换为JSON。 String json = JSON.toJSONString(jobDetail); // 4. 使用IndexRequest.source方法设置请求数据。 indexRequest.source(json); try { // 5. 使用ES High level client调用index方法发起请求 restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT); } catch (IOException e) { e.printStackTrace(); } System.out.println("索引创建成功!"); }
常见错误:
java.lang.IllegalArgumentException: The number of object passed must be even but was [1] at org.elasticsearch.action.index.IndexRequest.source(IndexRequest.java:474) at org.elasticsearch.action.index.IndexRequest.source(IndexRequest.java:461)
原因:IndexRequest.source要求传递偶数个的参数,但只传递了1个
参考代码:
public class JobFullTextServiceTest { private JobFullTextService jobFullTextService; @BeforeTest public void beforeTest() { jobFullTextService = new JobFullTextServiceImpl(); } @Test public void addTest() { // 1. 测试新增索引文档 jobFullTextService = new JobFullTextServiceImpl(); JobDetail jobDetail = new JobDetail(); jobDetail.setId(1); jobDetail.setArea("江苏省-南京市"); jobDetail.setCmp("Elasticsearch大学"); jobDetail.setEdu("本科及以上"); jobDetail.setExp("一年工作经验"); jobDetail.setTitle("大数据工程师"); jobDetail.setJob_type("全职"); jobDetail.setPv("1700次浏览"); jobDetail.setJd("会Hadoop就行"); jobDetail.setSalary("5-9千/月"); jobFullTextService.add(jobDetail); } @AfterTest public void afterTest() { jobFullTextService.close(); } }