Java elasticSearch-api的具体操作步骤讲解

时间:2022-04-08 04:31:05

使用步骤

1.环境准备

用的是windows版,自行下载

链接: 下载地址

2.针对索引操作

这里是kibana上操作的(也可以用postman操作):

Java elasticSearch-api的具体操作步骤讲解

  1. #创建索引,指定文档id
  2. PUT /test1/type1/1
  3. {
  4. "name":"张三",
  5. "age":30
  6.  
  7. }
  8. #创建索引规则(类似数据库建表)
  9. PUT /test2
  10. {
  11. "mappings": {
  12. "properties": {
  13. "name":{
  14. "type":"text"
  15. },
  16. "age":{
  17. "type": "integer"
  18. },
  19. "birthday":{
  20. "type": "date"
  21. }
  22. }
  23. }
  24. }
  25. #获取索引的信息,properties类型
  26. GET test2
  27. #创建索引,properties不指定类型会有默认类型
  28. #也可以用作修改,但是必须写上全部字段,不然会丢失未写字段
  29. PUT /test3/_doc/1
  30. {
  31. "name":"张三",
  32. "age":30,
  33. "birth":"1991-06-23"
  34. }
  35. GET test3
  36. #查看es健康状态
  37. GET _cat/health
  38. #查看所有索引状态
  39. GET _cat/indices?v
  40. #修改
  41. POST /test3/_doc/1/_update
  42. {
  43. "doc":{
  44. "name":"李四"
  45. }
  46. }

3.针对doc操作(增删改)

代码如下(示例):

  1. #新增索引,并添加doc
  2. POST /chen/user/1
  3. {
  4. "name":"张三",
  5. "age":11,
  6. "desc":"一顿操作猛如虎,一看工资2500",
  7. "tags":["技术宅","温暖","直男"]
  8. }
  9. POST /chen/user/2
  10. {
  11. "name":"李四",
  12. "age":12,
  13. "desc":"憨批",
  14. "tags":["渣男","旅游","交友"]
  15. }
  16. POST /chen/user/3
  17. {
  18. "name":"王五",
  19. "age":13,
  20. "desc":"瓜怂",
  21. "tags":["靓女","旅游","美食"]
  22. }
  23. POST /chen/user/4
  24. {
  25. "name":"刘六",
  26. "age":14,
  27. "desc":"锅盔",
  28. "tags":["衰仔","旅游","美食"]
  29. }
  30. #获取数据
  31. GET chen/user/1
  32. #更新数据
  33. POST chen/user/1/_update
  34. {
  35. "doc":{
  36. "name":"更新"
  37. }
  38. }
  39. #删除
  40. DELETE chen/user/1
  41. #条件查询,匹配度越高,_score(分值)越高
  42. GET chen/user/_search?q=name:李
  43. GET chen/user/_search?q=name:李四
  44. #等价于上面
  45. GET chen/user/_search
  46. {
  47. "query": {
  48. "match": {
  49. "name": "李四"
  50. }
  51. }
  52. }

4.针对doc操作(查)

查询1(示例):

  1. #_source结果过滤(指定需要字段结果集)
  2. #sort排序
  3. #from-size分页(类似limit )
  4. #注意:这个查询是不可以些多个字段的(我试过了)
  5. GET chen/user/_search
  6. {
  7. "query": {
  8. "match": {
  9. "name": "李四"
  10. }
  11. },
  12. "_source": ["name","age"],
  13. "sort": [
  14. {
  15. "age": {
  16. "order": "asc"
  17. }
  18. }
  19. ],
  20. "from":0,
  21. "size":1
  22. }
  23. #多条件精确查询
  24. #以下都是bool的二级属性
  25. #must:必须
  26. #should,满足任意条件
  27. #must_not,表示不满足
  28. GET chen/user/_search
  29. {
  30. "query": {
  31. "bool": {
  32. "must": [
  33. {"match": {
  34. "name": "李四"
  35. }},
  36. {"match": {
  37. "age": 11
  38. }}
  39. ]
  40. }
  41. }
  42. }
  43. #过滤.注意filter是bool(多条件)的二级属性
  44. GET chen/user/_search
  45. {
  46. "query": {
  47. "bool": {
  48. "must": [
  49. {"match": {
  50. "name": "李四"
  51. }}
  52. ],
  53. "filter": {
  54. "range": {
  55. "age": {
  56. "gte": 10,
  57. "lte": 20
  58. }
  59. }
  60. }
  61. }
  62. }
  63. }
  64. #分词器依然有效
  65. #多个条件空格隔开就行,只要满足其中一个,就会被逮到
  66. GET chen/user/_search
  67. {
  68. "query": {
  69. "match": {
  70. "tags": "男 技术"
  71. }
  72. }
  73. }
  74. #精确查询,结果只能为1,多条直接不显示
  75. GET chen/user/_search
  76. {
  77. "query": {
  78. "term": {
  79. "name": "李四"
  80. }
  81. }
  82. }

查询2(示例):

  1. #新建索引
  2. PUT test4
  3. {
  4. "mappings": {
  5. "properties": {
  6. "name":{
  7. "type": "text"
  8. },
  9. "desc":{
  10. "type": "keyword"
  11. }
  12. }
  13. }
  14. }
  15. #插入数据
  16. PUT test4/_doc/1
  17. {
  18. "name":"张三name",
  19. "desc":"张三desc"
  20. }
  21. PUT test4/_doc/2
  22. {
  23. "name":"张三name2",
  24. "desc":"张三desc2"
  25. }
  26. #分词器查询(并不是查询索引里的数据,而是将text的内容用分词器拆分的结果)
  27. GET _analyze
  28. {
  29. "analyzer": "keyword",
  30. "text": ["张三name"]
  31. }
  32. GET _analyze
  33. {
  34. "analyzer": "standard",
  35. "text": "张三name"
  36. }
  37. GET test4/_search
  38. {
  39. "query": {
  40. "term": {
  41. "name": "张"
  42. }
  43. }
  44. }
  45. #==keyword不会被分词器解析==
  46. GET test4/_search
  47. {
  48. "query": {
  49. "term": {
  50. "desc": "张三desc"
  51. }
  52. }
  53. }

查询3(示例):

  1. PUT test4/_doc/3
  2. {
  3. "t1":"22",
  4. "t2":"2020-4-6"
  5. }
  6. PUT test4/_doc/4
  7. {
  8. "t1":"33",
  9. "t2":"2020-4-7"
  10. }
  11. #精确查询多个值
  12. GET test4/_search
  13. {
  14. "query": {
  15. "bool": {
  16. "should": [
  17. {
  18. "term": {
  19. "t1": "22"
  20. }
  21. },
  22. {
  23. "term": {
  24. "t1": "33"
  25. }
  26. }
  27. ]
  28. }
  29. }
  30. }
  31. #highlight:高亮
  32. #pre_tags,post_tags:自定义高亮条件,前缀后缀
  33. GET chen/user/_search
  34. {
  35. "query": {
  36. "match": {
  37. "name": "李四"
  38. }
  39. },
  40. "highlight": {
  41. "pre_tags": "<p class='key' style='color:red'",
  42. "post_tags": "</p>",
  43. "fields": {
  44. "name":{}
  45. }
  46. }
  47. }

5.java-api

索引操作:

  1. public class ES_Index {
  2. private static final String HOST_NAME = "localhost";
  3. private static final Integer PORT = 9200;
  4. private static RestHighLevelClient client;
  5.  
  6. //创建ES客户端
  7. static {
  8. RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(HOST_NAME, PORT));
  9. client = new RestHighLevelClient(restClientBuilder);
  10. }
  11.  
  12. //关闭ES客户端
  13. public void close() {
  14. if (null != client) {
  15. try {
  16. client.close();
  17. } catch (IOException e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. }
  22. //创建索引
  23. public void addIndex() throws IOException {
  24. //创建索引
  25. CreateIndexRequest request = new CreateIndexRequest("chen");
  26. CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
  27. //响应状态
  28. System.out.println("索引创建操作: " + response.isAcknowledged());
  29. }
  30. //查询索引
  31. public void selectIndex() throws IOException {
  32. GetIndexRequest request = new GetIndexRequest("chen");
  33. GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
  34. System.out.println("索引查询操作: " +response.getAliases());
  35. System.out.println("索引查询操作: " +response.getMappings());
  36. System.out.println("索引查询操作: " +response.getSettings());
  37. }
  38. //删除索引
  39. public void deleteIndex() throws IOException {
  40. DeleteIndexRequest request = new DeleteIndexRequest("chen");
  41. AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
  42. System.out.println("索引删除操作: "+response.isAcknowledged());
  43. }
  44. public static void main(String[] args) throws IOException {
  45. ES_Index index=new ES_Index();
  46. //index.addIndex();
  47. //index.selectIndex();
  48. index.deleteIndex();
  49. index.close();
  50. }
  51. }

文档操作:

  1. public class ES_Doc {
  2. private static final String HOST_NAME = "localhost";
  3. private static final Integer PORT = 9200;
  4. private static RestHighLevelClient client;
  5.  
  6. //创建ES客户端
  7. static {
  8. RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(HOST_NAME, PORT));
  9. client = new RestHighLevelClient(restClientBuilder);
  10. }
  11.  
  12. //关闭ES客户端
  13. public void close() {
  14. if (null != client) {
  15. try {
  16. client.close();
  17. } catch (IOException e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. }
  22.  
  23. //插入数据
  24. public void addDoc() throws IOException {
  25. IndexRequest request = new IndexRequest();
  26. User user = new User("张三", "男", 18);
  27. //向es插入数据,必须将数据转换为json格式
  28. String userJson = new ObjectMapper().writeValueAsString(user);
  29. request.index("user").id("1001").source(userJson, XContentType.JSON);
  30. IndexResponse response = client.index(request, RequestOptions.DEFAULT);
  31. System.out.println("文档创建操作: " + response.getResult());
  32. }
  33.  
  34. //修改数据(局部修改)
  35. public void updateDoc() throws IOException {
  36. UpdateRequest request = new UpdateRequest();
  37. request.index("user").id("1001").doc(XContentType.JSON, "sex", "女");
  38. UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
  39. System.out.println("文档修改操作: " + response.getResult());
  40. }
  41.  
  42. //获取数据
  43. public void getDoc() throws IOException {
  44. GetRequest request = new GetRequest();
  45. request.index("user").id("1001");
  46. GetResponse response = client.get(request, RequestOptions.DEFAULT);
  47. User user = new ObjectMapper().readValue(response.getSourceAsString(), User.class);
  48. System.out.println("文档获取操作: " + user);
  49. }
  50.  
  51. //删除数据
  52. public void deleteDoc() throws IOException {
  53. DeleteRequest request = new DeleteRequest();
  54. request.index("user").id("1001");
  55. DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
  56. System.out.println("文档删除操作: " + response.getResult());
  57. }
  58.  
  59. //批量插入数据
  60. public void addBatch() throws IOException {
  61. BulkRequest request = new BulkRequest();
  62. request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "张三", "sex", "男", "age", 10));
  63. request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "李四", "sex", "男", "age", 20));
  64. request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "王五", "sex", "女", "age", 30));
  65. request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON, "name", "赵六", "sex", "男", "age", 40));
  66. request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON, "name", "孙七", "sex", "女", "age", 50));
  67. BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
  68. System.out.println("文档批量新增操作: " + response.getTook());
  69. System.out.println("文档批量新增操作: " + !response.hasFailures());//是否失败
  70. }
  71.  
  72. //批量删除数据
  73. public void deleteBatch() throws IOException {
  74. BulkRequest request = new BulkRequest();
  75. request.add(new DeleteRequest().index("user").id("1001"));
  76. request.add(new DeleteRequest().index("user").id("1002"));
  77. request.add(new DeleteRequest().index("user").id("1003"));
  78. request.add(new DeleteRequest().index("user").id("1004"));
  79. request.add(new DeleteRequest().index("user").id("1005"));
  80. BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
  81. System.out.println("文档批量删除操作: " + response.getTook());
  82. System.out.println("文档批量删除操作: " + !response.hasFailures());//是否失败
  83. }
  84.  
  85. //查询(重点)
  86. public void searchDoc() throws IOException {
  87. SearchRequest request = new SearchRequest();
  88. request.indices("user");
  89. //1.查询索引中的全部数据
  90. //request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
  91. //2.查询年龄为30的数据
  92. //request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age", 30)));
  93. //3.分页查询,当前第0页,每页两条
  94. //request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()).from(0).size(2));
  95. //4.排序,倒序
  96. //request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()).sort("age", SortOrder.DESC));
  97. //5.过滤字段(排除和包含,也可以是数组)
  98. //request.source(new SearchSourceBuilder().fetchSource("name", null));
  99. //6.组合查询
  100. //BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  101. //6.1 must相当于and
  102. //boolQueryBuilder.must(QueryBuilders.matchQuery("age", 30));
  103. //boolQueryBuilder.must(QueryBuilders.matchQuery("sex", "女"));
  104. //6.2 should相当于or
  105. //boolQueryBuilder.should(QueryBuilders.matchQuery("age", 30));
  106. //boolQueryBuilder.should(QueryBuilders.matchQuery("sex", "女"));
  107. //request.source(new SearchSourceBuilder().query(boolQueryBuilder));
  108. //7.范围查询
  109. //request.source(new SearchSourceBuilder().query(QueryBuilders.rangeQuery("age").gte(30).lte(40)));
  110. //8.模糊查询Fuzziness.ONE即只差1个字符
  111. //request.source(new SearchSourceBuilder().query(QueryBuilders.fuzzyQuery("name", "王五").fuzziness(Fuzziness.ONE)));
  112. //9.高亮显示
  113. //SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchPhraseQuery("name", "张三"));
  114. //builder.highlighter(new HighlightBuilder().preTags("<font color='red'>").postTags("</font>").field("name"));
  115. //request.source(builder);
  116. //10.聚合查询
  117. //SearchSourceBuilder builder = new SearchSourceBuilder();
  118. //MaxAggregationBuilder aggregationBuilder = AggregationBuilders.max("maxAge").field("age");
  119. //builder.aggregation(aggregationBuilder);
  120. //request.source(builder);
  121. //11.分组查询
  122. SearchSourceBuilder builder = new SearchSourceBuilder();
  123. TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("ageGroup").field("age");
  124. builder.aggregation(aggregationBuilder);
  125. request.source(builder);
  126. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  127. SearchHits hits = response.getHits();
  128. System.out.println("--条数: " + hits.getTotalHits());
  129. System.out.println("--用时: " + response.getTook());
  130. hits.forEach((item)->{
  131. System.out.println("--数据: " + item.getSourceAsString());
  132. });
  133. }
  134.  
  135. public static void main(String[] args) throws IOException {
  136. ES_Doc doc = new ES_Doc();
  137. //doc.addDoc();
  138. //doc.updateDoc();
  139. //doc.getDoc();
  140. //doc.deleteDoc();
  141. //doc.addBatch();
  142. //doc.deleteBatch();
  143. doc.searchDoc();
  144. doc.close();
  145. }
  146. }

6.spring-data-elasticsearch

实体类: 关键在于@Document和@Field注解
shards 代表分片
replicas 代表副本

  1. @Data
  2. @NoArgsConstructor
  3. @AllArgsConstructor
  4. @Document(indexName = "product", shards = 3, replicas = 1)
  5. public class Product {
  6. @Id
  7. private Long id;//商品唯一标识
  8. @Field(type = FieldType.Text)
  9. private String title;//商品名称
  10. @Field(type = FieldType.Keyword)
  11. private String category;//分类名称
  12. @Field(type = FieldType.Double)
  13. private Double price;//商品价格
  14. @Field(type = FieldType.Keyword,index = false)
  15. private String images;//图片地址
  16. }

dao层: 这样就已经可以了,类似mybatis-plus的BaseMapper,封装好了一些操作

  1. @Repository
  2. public interface ProductDao extends ElasticsearchRepository<Product,Long> {
  3. }

yaml :不用怎么配置,默认就去找localhost:9200

测试 :不知道为啥dao的很多方法都过时了,看源码注释让回去用elasticsearchRestTemplate,感觉更繁琐

  1. @SpringBootTest
  2. class ElasticsearchApplicationTests {
  3. @Autowired
  4. ElasticsearchRestTemplate elasticsearchRestTemplate;
  5. @Autowired
  6. ProductDao productDao;
  7.  
  8. @Test
  9. void createIndex() {
  10. //创建索引,系统初始化会自动创建索引
  11. System.out.println("创建索引");
  12. }
  13.  
  14. @Test
  15. void deleteIndex() {
  16. //创建索引,系统初始化会自动创建索引
  17. boolean flg = elasticsearchRestTemplate.deleteIndex(Product.class);
  18. System.out.println("删除索引 = " + flg);
  19. }
  20.  
  21. //新增数据
  22. @Test
  23. void addDoc() {
  24. Product product = new Product();
  25. product.setId(1001L);
  26. product.setTitle("华为手机");
  27. product.setCategory("手机");
  28. product.setPrice(2999.0);
  29. product.setImages("www.huawei.com");
  30. productDao.save(product);
  31. }
  32.  
  33. //修改
  34. @Test
  35. void updateDoc() {
  36. Product product = new Product();
  37. product.setId(1001L);
  38. product.setTitle("小米手机");
  39. product.setCategory("手机");
  40. product.setPrice(4999.0);
  41. product.setImages("www.xiaomi.com");
  42. productDao.save(product);
  43. }
  44.  
  45. //根据 id 查询
  46. @Test
  47. void findById() {
  48. Product product = productDao.findById(1001L).get();
  49. System.out.println(product);
  50. }
  51.  
  52. //查询所有
  53. @Test
  54. void findAll() {
  55. Iterable<Product> products = productDao.findAll();
  56. for (Product product : products) {
  57. System.out.println(product);
  58. }
  59. }
  60.  
  61. //删除
  62. @Test
  63. public void delete() {
  64. productDao.deleteById(1001L);
  65. }
  66.  
  67. //批量新增
  68. @Test
  69. public void saveAll() {
  70. List<Product> productList = new ArrayList<>();
  71. for (int i = 0; i < 10; i++) {
  72. Product product = new Product();
  73. product.setId((long) i);
  74. product.setTitle("[" + i + "]小米手机");
  75. product.setCategory("手机");
  76. product.setPrice(1999.0 + i);
  77. product.setImages("http://www.atguigu/xm.jpg");
  78. productList.add(product);
  79. }
  80. productDao.saveAll(productList);
  81. }
  82.  
  83. //分页查询
  84. @Test
  85. void findByPageable() {
  86. Sort orders = Sort.by(Sort.Direction.DESC, "id");
  87. Pageable pageable = PageRequest.of(0, 5, orders);
  88. Page<Product> products = productDao.findAll(pageable);
  89. products.forEach(System.out::println);
  90. }
  91.  
  92. /**
  93. * term 查询
  94. * search(termQueryBuilder) 调用搜索方法,参数查询构建器对象
  95. */
  96. @Test
  97. void termQuery() {
  98. TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("category", "手机");
  99. Iterable<Product> products = productDao.search(termQueryBuilder);
  100. products.forEach(System.out::println);
  101. }
  102.  
  103. /**
  104. * term 查询加分页
  105. */
  106. @Test
  107. void termQueryByPage() {
  108. PageRequest pageRequest = PageRequest.of(0, 5);
  109. TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("category", "手机");
  110. Iterable<Product> products = productDao.search(termQueryBuilder, pageRequest);
  111. products.forEach(System.out::println);
  112. }
  113. }

到此这篇关于elasticSearch-api的具体操作步骤讲解的文章就介绍到这了,更多相关elasticSearch-api详解内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_51138261/article/details/116139372