引入

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.elasticsearch</groupId>
  4. <artifactId>elasticsearch</artifactId>
  5. <version>5.6.8</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.elasticsearch.client</groupId>
  9. <artifactId>transport</artifactId>
  10. <version>5.6.8</version>
  11. </dependency>
  12. </dependencies>
  13. <dependency>
  14. <groupId>com.fasterxml.jackson.core</groupId>
  15. <artifactId>jackson-databind</artifactId>
  16. <version>2.8.1</version>
  17. </dependency>

索引库

新建

  1. @Test
  2. public void createIndex() throws Exception {
  3. //1、创建一个Settings对象,需要设置一个“cluster.name”属性
  4. Settings settings = Settings.builder()
  5. .put("cluster.name", "my-elasticsearch")
  6. .build();
  7. //2、创建一个TransportClient对象,PreBuilderTransportClient类创建对象,需要Settings对象
  8. TransportClient client = new PreBuiltTransportClient(settings);
  9. //3、向TransportClient对象中设置集群中的node列表
  10. client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
  11. client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
  12. client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
  13. //4、使用TransportClient创建索引库
  14. client.admin().indices()
  15. //设置索引库的名称
  16. .prepareCreate("blog")
  17. //执行操作
  18. .get();
  19. //5、关闭TransportClient对象
  20. client.close();
  21. }

删除index

  1. client.admin().indices()
  2. .prepareDelete("hello")
  3. .get();

设置mapping

设置index之后设置mapping

  1. @Test
  2. public void putMapping() throws Exception {
  3. // 创建json对象
  4. XContentBuilder builder = XContentFactory.jsonBuilder()
  5. .startObject()
  6. .startObject("article")
  7. .startObject("properties")
  8. .startObject("id")
  9. .field("type", "long")
  10. .field("index", true)
  11. .field("store", "true")
  12. .endObject()
  13. .startObject("title")
  14. .field("type", "text")
  15. .field("store", "true")
  16. .field("analyzer", "ik_max_word")
  17. .endObject()
  18. .startObject("content")
  19. .field("type", "text")
  20. .field("store", "true")
  21. .field("analyzer", "ik_max_word")
  22. .endObject()
  23. .endObject()
  24. .endObject()
  25. .endObject();
  26. // 使用client对象设置mapping信息
  27. client.admin().indices()
  28. //设置要向哪个索引库中设置mapping
  29. .preparePutMapping("blog")
  30. //设置mapping的type名称
  31. .setType("article")
  32. //设置mapping的json数据
  33. .setSource(builder)
  34. //执行操作
  35. .get();
  36. //关闭client
  37. client.close();
  38. }

创建index的时候设置mapping

  1. client.admin().indices()
  2. //新建索引库的名称
  3. .prepareCreate("blog2")
  4. //设置mapping信息。后面是枚举类型
  5. .setSource(mapping, XContentType.JSON)
  6. .get();

aliase

  1. logESIndex.addAliase("log_index", "log_index_all");
  2. logESIndex.addAliase("log_index2", "log_index_all");

文档

新建

方式1:直接新建

  1. XContentBuilder builder = XContentFactory.jsonBuilder()
  2. .startObject()
  3. .field("id", 1)
  4. .field("title","测试文档的标题")
  5. .field("content", "测试文档的内容")
  6. .endObject();
  7. // 使用client对象将文档写入索引库
  8. client.prepareIndex()
  9. //.prepareIndex("blog", "article")
  10. //设置操作的索引库
  11. .setIndex("blog")
  12. //设置type名称
  13. .setType("article")
  14. //设置文档的id(_id)
  15. .setId("1")
  16. //设置文档信息
  17. .setSource(builder)
  18. //执行操作
  19. .get();

方式2:使用对象新建

  1. ObjectMapper objectMapper = new ObjectMapper();
  2. //使用Objectmapper对象将java对象转换成json字符串
  3. String json = objectMapper.writeValueAsString(article);
  4. //使用client对象将文档写入索引库
  5. client.prepareIndex("blog", "article", "2")
  6. .setSource(json, XContentType.JSON)
  7. .get();

删除

  1. client.prepareDelete("blog", "article", "1")
  2. //执行操作
  3. .get();

修改

方式一:和新建一摸一样

  1. client.prepareIndex("blog","article", "2")
  2. .setSource(json, XContentType.JSON)
  3. .get();

方式二:使用prepareUpdate

  1. client.prepareUpdate("blog", "article", "2")
  2. .setDoc(json, XContentType.JSON)
  3. .get();

搜索

  1. # 精确搜索
  2. TermQueryBuilder builder = QueryBuilders.termQuery("title", "测试文档的标题");
  3. # 正则搜索
  4. RegexpQueryBuilder builder = QueryBuilders.regexpQuery("title", ".*"+"文档的标题"+".*");
  5. # 排序
  6. searchRequestBuilder.addSort("publish_time", SortOrder.DESC);
  7. # 普通搜索
  8. SearchResponse searchResponse = logESIndex.getClient()
  9. .prepareSearch("log_index_all")
  10. .setQuery(builder)
  11. .addSort("field", SortOrder.ASC)
  12. .get();
  13. # 分组
  14. # select field1, field2, sum(field3) from table_name group by field1, field2;
  15. SearchResponse response = client.prepareSearch("test_index").setTypes("tweet")
  16. .addAggregation(AggregationBuilders.terms("userAgg").field("user.keyword")
  17. .subAggregation(AggregationBuilders.terms("sexAgg").field("sex.keyword")
  18. .subAggregation(AggregationBuilders.sum("sumAgg").field("age")))) //求和要放到最内层的分组语句里面
  19. //4、取查询结果
  20. SearchHits searchHits = searchResponse.getHits();
  21. //5、可以取查询结果的总记录数
  22. System.out.println("查询结果的总记录数:" + searchHits.getTotalHits());
  23. //6、取结果列表
  24. SearchHit[] hits = searchHits.getHits();
  25. for (SearchHit hit : hits) {
  26. Map<String, Object> source = hit.getSource();
  27. System.out.println(source);
  28. }

查询

根据id查询示例

  1. @Test
  2. public void searchById() throws Exception {
  3. //1、创建一个client对象
  4. //2、创建QueryBuilder查询对象
  5. QueryBuilder builder = QueryBuilders.idsQuery()
  6. .addIds("2");
  7. //3、使用client的prepareQuery方法,执行查询
  8. //设置查询的索引库
  9. SearchResponse searchResponse = client.prepareSearch("blog")
  10. //设置查询的type
  11. .setTypes("article")
  12. //设置查询条件
  13. .setQuery(builder)
  14. //执行查询
  15. .get();
  16. //4、取查询结果
  17. SearchHits searchHits = searchResponse.getHits();
  18. //5、可以取查询结果的总记录数
  19. System.out.println("查询结果的总记录数:" + searchHits.getTotalHits());
  20. //6、取结果列表
  21. SearchHit[] hits = searchHits.getHits();
  22. for (SearchHit hit : hits) {
  23. Map<String, Object> source = hit.getSource();
  24. System.out.println(source);
  25. }
  26. //7、关闭client
  27. client.close();
  28. }

关键词查询TermQuery

  1. QueryBuilder builder = QueryBuilders.termQuery("title", "寿星老");

QueryString查询

  1. QueryBuilder builder = QueryBuilders.queryStringQuery("央行连续11日暂停公开市场操作").defaultField("title");

分页查询

设置起始行和size即可

  1. SearchResponse searchResponse = client.prepareSearch("blog")
  2. //设置查询的type
  3. .setTypes("article")
  4. //设置查询条件
  5. .setQuery(builder)
  6. //设置分页信息,起始的行号
  7. .setFrom(0)
  8. //每页显示的行数
  9. .setSize(3)
  10. //执行查询
  11. .get();

高亮显示

  1. @Test
  2. public void searchByTermWithHighlighing() throws Exception {
  3. QueryBuilder builder = QueryBuilders.termQuery("title", "人民币");
  4. //3、使用client的prepareQuery方法,执行查询
  5. //创建高亮显示的Builder对象
  6. HighlightBuilder highlightBuilder = new HighlightBuilder()
  7. //设置高亮显示的域
  8. .field("title")
  9. //前缀
  10. .preTags("<em>")
  11. //后缀
  12. .postTags("</em>");
  13. //设置查询的索引库
  14. SearchResponse searchResponse = client.prepareSearch("blog")
  15. //设置查询的type
  16. .setTypes("article")
  17. //设置查询条件
  18. .setQuery(builder)
  19. //设置分页信息,起始的行号
  20. .setFrom(0)
  21. //每页显示的行数
  22. .setSize(3)
  23. //设置高亮信息
  24. .highlighter(highlightBuilder)
  25. //执行查询
  26. .get();
  27. //4、取查询结果
  28. SearchHits searchHits = searchResponse.getHits();
  29. //5、可以取查询结果的总记录数
  30. System.out.println("查询结果的总记录数:" + searchHits.getTotalHits());
  31. //6、取结果列表
  32. SearchHit[] hits = searchHits.getHits();
  33. for (SearchHit hit : hits) {
  34. //获得返回的文档对象,使用map表示
  35. Map<String, Object> source = hit.getSource();
  36. //当前文档对象高亮的结果
  37. Map<String, HighlightField> highlightFields = hit.getHighlightFields();
  38. System.out.println(source);
  39. System.out.println(highlightFields);
  40. //根据高亮显示的域的名称取结果
  41. Text title = highlightFields.get("title").getFragments()[0];
  42. System.out.println(title);
  43. }
  44. //7、关闭client
  45. client.close();
  46. }