前提:

1、ES服务成功启动

  

2、node.js成功启动

  

一、创建索引库

1、目录展示

  

2、导入依赖

  1. <dependency>
  2. <groupId>org.elasticsearch</groupId>
  3. <artifactId>elasticsearch</artifactId>
  4. <version>5.6.8</version>
  5. </dependency>
  6.  
  7. <dependency>
  8. <groupId>org.elasticsearch.client</groupId>
  9. <artifactId>transport</artifactId>
  10. <version>5.6.8</version>
  11. </dependency>
  12.  
  13. <dependency>
  14. <groupId>org.apache.logging.log4j</groupId>
  15. <artifactId>log4j-to-slf4j</artifactId>
  16. <version>2.9.1</version>
  17. </dependency>
  18.  
  19. <dependency>
  20. <groupId>org.slf4j</groupId>
  21. <artifactId>slf4j-api</artifactId>
  22. <version>1.7.24</version>
  23. </dependency>
  24.  
  25. <dependency>
  26. <groupId>org.slf4j</groupId>
  27. <artifactId>slf4j-simple</artifactId>
  28. <version>1.7.21</version>
  29. </dependency>
  30.  
  31. <dependency>
  32. <groupId>log4j</groupId>
  33. <artifactId>log4j</artifactId>
  34. <version>1.2.12</version>
  35. </dependency>

3、MyESTest代码

  1. package com.zn;
  2.  
  3. import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
  4. import org.elasticsearch.client.Requests;
  5. import org.elasticsearch.client.transport.TransportClient;
  6. import org.elasticsearch.common.settings.Settings;
  7. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  8. import org.elasticsearch.common.xcontent.XContentBuilder;
  9. import org.elasticsearch.common.xcontent.XContentFactory;
  10. import org.elasticsearch.transport.client.PreBuiltTransportClient;
  11. import org.junit.jupiter.api.Test;
  12.  
  13. import java.io.IOException;
  14. import java.net.InetAddress;
  15. import java.net.UnknownHostException;
  16. import java.util.concurrent.ExecutionException;
  17.  
  18. public class MyESTest {
  19.  
  20. /**
  21. * 创建索引
  22. * @throws UnknownHostException
  23. */
  24. @Test
  25. public void creatIndex() throws UnknownHostException {
  26. //创建Client连接对象
  27. Settings settings = Settings.builder().put("cluster.name", "my-application").build();
  28. //设置IP地址和端口号
  29. TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
  30. new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
  31. //创建名称为es_test1的索引
  32. client.admin().indices().prepareCreate("es_test1").get();
  33. //释放资源
  34. client.close();
  35. }
  36. }

4、修改elasticsearch.yml配置文件

  cluster.name与代码块中cluster.name必须一致!!

  

5、重启elasticsearch

6、控制台效果

  

7、访问localhost:9100查看

  

  

二、创建映射mapping

1、MyESTest代码

  1. package com.zn;
  2.  
  3. import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
  4. import org.elasticsearch.client.Requests;
  5. import org.elasticsearch.client.transport.TransportClient;
  6. import org.elasticsearch.common.settings.Settings;
  7. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  8. import org.elasticsearch.common.xcontent.XContentBuilder;
  9. import org.elasticsearch.common.xcontent.XContentFactory;
  10. import org.elasticsearch.transport.client.PreBuiltTransportClient;
  11. import org.junit.jupiter.api.Test;
  12.  
  13. import java.io.IOException;
  14. import java.net.InetAddress;
  15. import java.net.UnknownHostException;
  16. import java.util.concurrent.ExecutionException;
  17.  
  18. public class MyESTest {
  19.  
  20. /**
  21. * 创建映射mapping
  22. */
  23. @Test
  24. public void creatMapping() throws IOException, ExecutionException, InterruptedException {
  25. //创建Client连接对象
  26. Settings settings = Settings.builder().put("cluster.name", "my-application").build();
  27. //设置IP地址和端口号
  28. TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
  29. new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
  30.  
  31. //添加映射
  32. XContentBuilder builder= XContentFactory.jsonBuilder()
  33. .startObject()
  34. .startObject("article")
  35. .startObject("properties")
  36. .startObject("id")
  37. .field("type","integer").field("store","yes")
  38. .endObject()
  39. .startObject("title")
  40. .field("type","string").field("store","yes").field("analyzer","ik_smart")
  41. .endObject()
  42. .startObject("content")
  43. .field("type","string").field("store","yes").field("analyzer","ik_smart")
  44. .endObject()
  45. .endObject()
  46. .endObject()
  47. .endObject();
  48. //创建映射
  49. PutMappingRequest mappingRequest= Requests.putMappingRequest("es_test1").type("article").source(builder);
  50. client.admin().indices().putMapping(mappingRequest).get();
  51. //释放资源
  52. client.close();
  53. }
  54. }

2、访问localhost:9100查看

  

3、查看mappings

  

三、创建索引库指定Mapping信息

1、MyESTest代码

  1. package com.zn.myTest;
  2.  
  3. import com.fasterxml.jackson.core.JsonProcessingException;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import com.zn.entity.Article;
  6. import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
  7. import org.elasticsearch.action.search.SearchRequestBuilder;
  8. import org.elasticsearch.action.search.SearchResponse;
  9. import org.elasticsearch.client.Requests;
  10. import org.elasticsearch.client.transport.TransportClient;
  11. import org.elasticsearch.common.settings.Settings;
  12. import org.elasticsearch.common.text.Text;
  13. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  14. import org.elasticsearch.common.xcontent.XContentBuilder;
  15. import org.elasticsearch.common.xcontent.XContentFactory;
  16. import org.elasticsearch.common.xcontent.XContentType;
  17. import org.elasticsearch.index.query.QueryBuilders;
  18. import org.elasticsearch.search.SearchHit;
  19. import org.elasticsearch.search.SearchHits;
  20. import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
  21. import org.elasticsearch.transport.client.PreBuiltTransportClient;
  22. import org.junit.jupiter.api.Test;
  23.  
  24. import java.io.IOException;
  25. import java.net.InetAddress;
  26. import java.net.UnknownHostException;
  27. import java.util.Iterator;
  28. import java.util.concurrent.ExecutionException;
  29.  
  30. public class MyESTest {
  31.  
  32. /**
  33. * 创建索引库指定Mapping信息
  34. */
  35. @Test
  36. public void createIndexAndMapping() throws IOException {
  37. //创建Client连接对象
  38. Settings settings = Settings.builder().put("cluster.name", "my-application").build();
  39. //设置IP地址和端口号
  40. TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
  41. new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
  42. //创建索引库
  43. client.admin().indices().prepareCreate("es_test2").get();
  44. //创建Mapping信息
  45. //创建一个XContentBuilder对象,用于拼接JSON格式字符串
  46. XContentBuilder xContentBuilder = XContentFactory.jsonBuilder();
  47. xContentBuilder.startObject().startObject("article1").startObject("properties")
  48. .startObject("id").field("type","integer").field("store","yes").field("index","not_analyzed")
  49. .endObject()
  50. .startObject("title").field("type","text").field("store","yes").field("index","analyzed").field("analyzer","ik_max_word")
  51. .endObject()
  52. .startObject("content").field("type","text").field("store","yes").field("index","analyzed").field("analyzer","ik_max_word")
  53. .endObject()
  54. .endObject().endObject().endObject();
  55.  
  56. client.admin().indices().preparePutMapping("es_test2").setType("article1").setSource(xContentBuilder).get();
  57.  
  58. //关闭资源
  59. client.close();
  60. }
  61.  
  62. }

2、访问localhost:9100查看

  

  

四、删除索引库

1、MyESTest代码

  1. package com.zn.myTest;
  2.  
  3. import com.fasterxml.jackson.core.JsonProcessingException;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import com.zn.entity.Article;
  6. import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
  7. import org.elasticsearch.action.search.SearchRequestBuilder;
  8. import org.elasticsearch.action.search.SearchResponse;
  9. import org.elasticsearch.client.Requests;
  10. import org.elasticsearch.client.transport.TransportClient;
  11. import org.elasticsearch.common.settings.Settings;
  12. import org.elasticsearch.common.text.Text;
  13. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  14. import org.elasticsearch.common.xcontent.XContentBuilder;
  15. import org.elasticsearch.common.xcontent.XContentFactory;
  16. import org.elasticsearch.common.xcontent.XContentType;
  17. import org.elasticsearch.index.query.QueryBuilders;
  18. import org.elasticsearch.search.SearchHit;
  19. import org.elasticsearch.search.SearchHits;
  20. import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
  21. import org.elasticsearch.transport.client.PreBuiltTransportClient;
  22. import org.junit.jupiter.api.Test;
  23.  
  24. import java.io.IOException;
  25. import java.net.InetAddress;
  26. import java.net.UnknownHostException;
  27. import java.util.Iterator;
  28. import java.util.concurrent.ExecutionException;
  29.  
  30. public class MyESTest {
  31.  
  32. /**
  33. * 删除索引库
  34. */
  35. @Test
  36. public void deleteIndex() throws UnknownHostException {
  37. //创建Client连接对象
  38. Settings settings = Settings.builder().put("cluster.name", "my-application").build();
  39. //设置IP地址和端口号
  40. TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
  41. new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
  42. //删除索引库
  43. client.admin().indices().prepareDelete("es_test2").get();
  44.  
  45. //关闭资源
  46. client.close();
  47. }
  48.  
  49. }

2、删除前

  

3、删除后

  

五、通过XContentBuilder建立文档document

1、MyESTest代码

  1. package com.zn;
  2.  
  3. import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
  4. import org.elasticsearch.client.Requests;
  5. import org.elasticsearch.client.transport.TransportClient;
  6. import org.elasticsearch.common.settings.Settings;
  7. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  8. import org.elasticsearch.common.xcontent.XContentBuilder;
  9. import org.elasticsearch.common.xcontent.XContentFactory;
  10. import org.elasticsearch.transport.client.PreBuiltTransportClient;
  11. import org.junit.jupiter.api.Test;
  12.  
  13. import java.io.IOException;
  14. import java.net.InetAddress;
  15. import java.net.UnknownHostException;
  16. import java.util.concurrent.ExecutionException;
  17.  
  18. public class MyESTest {
  19.  
  20. /**
  21. * 通过XContentBuilder创建文档document
  22. */
  23. @Test
  24. public void createXContentBuilderDocument() throws IOException {
  25. //创建Client连接对象
  26. Settings settings = Settings.builder().put("cluster.name", "my-application").build();
  27. //设置IP地址和端口号
  28. TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
  29. new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
  30.  
  31. //创建文档信息
  32. XContentBuilder builder = XContentFactory.jsonBuilder()
  33. .startObject()
  34. .field("id", 1)
  35. .field("title", "ElasticSearch是一个基于Lucene的搜索服务器")
  36. .field("content",
  37. "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。" +
  38. "Elasticsearch是用 Java开发的,并作为Apache许可条款下的开放源码发布," +
  39. "是当前流行的企业级搜索引擎。设计用于云计算中,能够达到 实时搜索,稳定,可靠,快速,安装使用方便。")
  40. .endObject();
  41. //创建文档对象
  42. //参数一:索引对象;参数二:类型;参数三:建立id
  43. client.prepareIndex("es_test1", "article", "1").setSource(builder).get();
  44. //释放资源
  45. client.close();
  46. }
  47. }

2、访问localhost:9100查看

  

六、使用Jackson转换实体建立文档document

1、目录展示

  

2、创建Article实体

  1. package com.zn.entity;
  2.  
  3. public class Article {
  4.  
  5. private Integer id;
  6. private String title;
  7. private String content;
  8.  
  9. public Integer getId() {
  10. return id;
  11. }
  12.  
  13. public void setId(Integer id) {
  14. this.id = id;
  15. }
  16.  
  17. public String getTitle() {
  18. return title;
  19. }
  20.  
  21. public void setTitle(String title) {
  22. this.title = title;
  23. }
  24.  
  25. public String getContent() {
  26. return content;
  27. }
  28.  
  29. public void setContent(String content) {
  30. this.content = content;
  31. }
  32. }

3、添加jackson坐标 (导入依赖)

  

  1. <dependency>
  2. <groupId>com.fasterxml.jackson.core</groupId>
  3. <artifactId>jackson-core</artifactId>
  4. <version>2.8.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.fasterxml.jackson.core</groupId>
  8. <artifactId>jackson-databind</artifactId>
  9. <version>2.8.1</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>com.fasterxml.jackson.core</groupId>
  13. <artifactId>jackson-annotations</artifactId>
  14. <version>2.8.1</version>
  15. </dependency>

4、MyESTest代码

  1. package com.zn.myTest;
  2.  
  3. import com.fasterxml.jackson.core.JsonProcessingException;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import com.zn.entity.Article;
  6. import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
  7. import org.elasticsearch.client.Requests;
  8. import org.elasticsearch.client.transport.TransportClient;
  9. import org.elasticsearch.common.settings.Settings;
  10. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  11. import org.elasticsearch.common.xcontent.XContentBuilder;
  12. import org.elasticsearch.common.xcontent.XContentFactory;
  13. import org.elasticsearch.common.xcontent.XContentType;
  14. import org.elasticsearch.transport.client.PreBuiltTransportClient;
  15. import org.junit.jupiter.api.Test;
  16.  
  17. import java.io.IOException;
  18. import java.net.InetAddress;
  19. import java.net.UnknownHostException;
  20. import java.util.concurrent.ExecutionException;
  21.  
  22. public class MyESTest {
  23. /**
  24. * 使用Jackson转换实体建立文档document
  25. */
  26. @Test
  27. public void creatJacksonDocument() throws UnknownHostException, JsonProcessingException {
  28. //创建Client连接对象
  29. Settings settings = Settings.builder().put("cluster.name", "my-application").build();
  30. //设置IP地址和端口号
  31. TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
  32. new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
  33.  
  34. //描述json 数据
  35. Article article = new Article();
  36. article.setId(2);
  37. article.setTitle("搜索工作其实很快乐");
  38. article.setContent("我们希望我们的搜索解决方案要快,我们希望有一个零配置和一个完全免费的搜索模式");
  39.  
  40. ObjectMapper objectMapper=new ObjectMapper();
  41.  
  42. //创建文档
  43. client.prepareIndex("es_test1","article",article.getId().toString())
  44. .setSource(objectMapper.writeValueAsString(article).getBytes(),
  45. XContentType.JSON).get();
  46.  
  47. //释放资源
  48. client.close();
  49.  
  50. }
  51. }

5、访问localhost:9100查看

  

七、关键词查询文档document

1、MyESTest代码

  1. package com.zn.myTest;
  2.  
  3. import com.fasterxml.jackson.core.JsonProcessingException;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import com.zn.entity.Article;
  6. import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
  7. import org.elasticsearch.action.search.SearchRequestBuilder;
  8. import org.elasticsearch.action.search.SearchResponse;
  9. import org.elasticsearch.client.Requests;
  10. import org.elasticsearch.client.transport.TransportClient;
  11. import org.elasticsearch.common.settings.Settings;
  12. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  13. import org.elasticsearch.common.xcontent.XContentBuilder;
  14. import org.elasticsearch.common.xcontent.XContentFactory;
  15. import org.elasticsearch.common.xcontent.XContentType;
  16. import org.elasticsearch.index.query.QueryBuilders;
  17. import org.elasticsearch.search.SearchHit;
  18. import org.elasticsearch.search.SearchHits;
  19. import org.elasticsearch.transport.client.PreBuiltTransportClient;
  20. import org.junit.jupiter.api.Test;
  21.  
  22. import java.io.IOException;
  23. import java.net.InetAddress;
  24. import java.net.UnknownHostException;
  25. import java.util.Iterator;
  26. import java.util.concurrent.ExecutionException;
  27.  
  28. public class MyESTest {
  29. /**
  30. * 关键词查询文档document
  31. */
  32. @Test
  33. public void selectWordDocument() throws UnknownHostException {
  34. //创建Client连接对象
  35. Settings settings = Settings.builder().put("cluster.name", "my-application").build();
  36. //设置IP地址和端口号
  37. TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
  38. new InetSocketTransportAddress(InetAddress.
  39. getByName("127.0.0.1"), 9300));
  40.  
  41. //设置搜索条件
  42. SearchResponse searchResponse = client.prepareSearch("es_test1")
  43. .setTypes("article")
  44. .setQuery(QueryBuilders.termQuery("content","搜索")).get();
  45.  
  46. //获取命中次数,查询结果有多少对象
  47. SearchHits hits = searchResponse.getHits();
  48. System.out.println("查询结果有:"+hits.getTotalHits()+"条");
  49. //遍历搜索结果数据
  50. Iterator<SearchHit> iterator = hits.iterator();
  51. while (iterator.hasNext()){
  52. //每个查询对象
  53. SearchHit searchHit = iterator.next();
  54. //获取字符串格式打印
  55. System.out.println(searchHit.getSourceAsString());
  56. System.out.println("title:"+searchHit.getSource().get("title"));
  57. }
  58.  
  59. //释放资源
  60. client.close();
  61.  
  62. }
  63. }

2、控制台

  

八、字符串查询文档document

1、MyESTest代码

  1. package com.zn.myTest;
  2.  
  3. import com.fasterxml.jackson.core.JsonProcessingException;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import com.zn.entity.Article;
  6. import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
  7. import org.elasticsearch.action.search.SearchResponse;
  8. import org.elasticsearch.client.Requests;
  9. import org.elasticsearch.client.transport.TransportClient;
  10. import org.elasticsearch.common.settings.Settings;
  11. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  12. import org.elasticsearch.common.xcontent.XContentBuilder;
  13. import org.elasticsearch.common.xcontent.XContentFactory;
  14. import org.elasticsearch.common.xcontent.XContentType;
  15. import org.elasticsearch.index.query.QueryBuilders;
  16. import org.elasticsearch.search.SearchHit;
  17. import org.elasticsearch.search.SearchHits;
  18. import org.elasticsearch.transport.client.PreBuiltTransportClient;
  19. import org.junit.jupiter.api.Test;
  20.  
  21. import java.io.IOException;
  22. import java.net.InetAddress;
  23. import java.net.UnknownHostException;
  24. import java.util.Iterator;
  25. import java.util.concurrent.ExecutionException;
  26.  
  27. public class MyESTest {
  28.  
  29. /**
  30. * 字符串查询文档document
  31. */
  32. @Test
  33. public void selectStringDocument() throws UnknownHostException {
  34. //创建Client连接对象
  35. Settings settings = Settings.builder().put("cluster.name", "my-application").build();
  36. //设置IP地址和端口号
  37. TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
  38. new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
  39.  
  40. //设置搜索条件
  41. SearchResponse searchResponse = client.prepareSearch("es_test1")
  42. .setTypes("article")
  43. .setQuery(QueryBuilders.queryStringQuery("搜索")).get();
  44.  
  45. //获取命中次数,查询结果有多少对象
  46. SearchHits hits = searchResponse.getHits();
  47. System.out.println("查询结果有:"+hits.getTotalHits()+"条");
  48. //遍历搜索结果数据
  49. Iterator<SearchHit> iterator = hits.iterator();
  50. while (iterator.hasNext()){
  51. //每个查询对象
  52. SearchHit searchHit = iterator.next();
  53. //获取字符串格式打印
  54. System.out.println(searchHit.getSourceAsString());
  55. System.out.println("title:"+searchHit.getSource().get("title"));
  56. }
  57. //释放资源
  58. client.close();
  59. }
  60. }

2、控制台

  

九、使用文档id查询文档

1、MyESTest代码

  1. package com.zn.myTest;
  2.  
  3. import com.fasterxml.jackson.core.JsonProcessingException;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import com.zn.entity.Article;
  6. import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
  7. import org.elasticsearch.action.search.SearchResponse;
  8. import org.elasticsearch.client.Requests;
  9. import org.elasticsearch.client.transport.TransportClient;
  10. import org.elasticsearch.common.settings.Settings;
  11. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  12. import org.elasticsearch.common.xcontent.XContentBuilder;
  13. import org.elasticsearch.common.xcontent.XContentFactory;
  14. import org.elasticsearch.common.xcontent.XContentType;
  15. import org.elasticsearch.index.query.QueryBuilders;
  16. import org.elasticsearch.search.SearchHit;
  17. import org.elasticsearch.search.SearchHits;
  18. import org.elasticsearch.transport.client.PreBuiltTransportClient;
  19. import org.junit.jupiter.api.Test;
  20.  
  21. import java.io.IOException;
  22. import java.net.InetAddress;
  23. import java.net.UnknownHostException;
  24. import java.util.Iterator;
  25. import java.util.concurrent.ExecutionException;
  26.  
  27. public class MyESTest {
  28.  
  29. /**
  30. * 使用文档id查询文档
  31. */
  32. @Test
  33. public void selectIdDocument() throws UnknownHostException {
  34. //创建Client连接对象
  35. Settings settings = Settings.builder().put("cluster.name", "my-application").build();
  36. //设置IP地址和端口号
  37. TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
  38. new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
  39.  
  40. //设置搜索条件
  41. SearchResponse searchResponse = client.prepareSearch("es_test1")
  42. .setTypes("article")
  43. .setQuery(QueryBuilders.idsQuery().addIds("2")).get();
  44. //获取命中次数,查询结果有多少对象
  45. SearchHits hits = searchResponse.getHits();
  46. System.out.println("查询结果有:"+hits.getTotalHits()+"条");
  47. //遍历搜索结果数据
  48. Iterator<SearchHit> iterator = hits.iterator();
  49. while (iterator.hasNext()){
  50. //每个查询对象
  51. SearchHit searchHit = iterator.next();
  52. //获取字符串格式打印
  53. System.out.println(searchHit.getSourceAsString());
  54. System.out.println("title:"+searchHit.getSource().get("title"));
  55. }
  56. //释放资源
  57. client.close();
  58. }
  59. }

2、控制台

  

十、删除文档

1、MyESTest代码

  1. package com.zn.myTest;
  2.  
  3. import com.fasterxml.jackson.core.JsonProcessingException;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import com.zn.entity.Article;
  6. import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
  7. import org.elasticsearch.action.search.SearchRequestBuilder;
  8. import org.elasticsearch.action.search.SearchResponse;
  9. import org.elasticsearch.client.Requests;
  10. import org.elasticsearch.client.transport.TransportClient;
  11. import org.elasticsearch.common.settings.Settings;
  12. import org.elasticsearch.common.text.Text;
  13. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  14. import org.elasticsearch.common.xcontent.XContentBuilder;
  15. import org.elasticsearch.common.xcontent.XContentFactory;
  16. import org.elasticsearch.common.xcontent.XContentType;
  17. import org.elasticsearch.index.query.QueryBuilders;
  18. import org.elasticsearch.search.SearchHit;
  19. import org.elasticsearch.search.SearchHits;
  20. import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
  21. import org.elasticsearch.transport.client.PreBuiltTransportClient;
  22. import org.junit.jupiter.api.Test;
  23.  
  24. import java.io.IOException;
  25. import java.net.InetAddress;
  26. import java.net.UnknownHostException;
  27. import java.util.Iterator;
  28. import java.util.concurrent.ExecutionException;
  29.  
  30. public class MyESTest {
  31.  
  32. /**
  33. * 删除文档
  34. */
  35. @Test
  36. public void deleteDocument() throws UnknownHostException, JsonProcessingException {
  37. //创建Client连接对象
  38. Settings settings = Settings.builder().put("cluster.name", "my-application").build();
  39. //设置IP地址和端口号
  40. TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
  41. new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
  42.  
  43. //删除文档
  44. client.prepareDelete("es_test1","article","14").get();
  45.  
  46. client.close();
  47. }
  48.  
  49. }

2、删除前

  

3、删除后

  

十一、查询文档分页操作

1、批量插入数据

  1. package com.zn.myTest;
  2.  
  3. import com.fasterxml.jackson.core.JsonProcessingException;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import com.zn.entity.Article;
  6. import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
  7. import org.elasticsearch.action.search.SearchResponse;
  8. import org.elasticsearch.client.Requests;
  9. import org.elasticsearch.client.transport.TransportClient;
  10. import org.elasticsearch.common.settings.Settings;
  11. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  12. import org.elasticsearch.common.xcontent.XContentBuilder;
  13. import org.elasticsearch.common.xcontent.XContentFactory;
  14. import org.elasticsearch.common.xcontent.XContentType;
  15. import org.elasticsearch.index.query.QueryBuilders;
  16. import org.elasticsearch.search.SearchHit;
  17. import org.elasticsearch.search.SearchHits;
  18. import org.elasticsearch.transport.client.PreBuiltTransportClient;
  19. import org.junit.jupiter.api.Test;
  20.  
  21. import java.io.IOException;
  22. import java.net.InetAddress;
  23. import java.net.UnknownHostException;
  24. import java.util.Iterator;
  25. import java.util.concurrent.ExecutionException;
  26.  
  27. public class MyESTest {
  28.  
  29. /**
  30. * 查询文档分页操作---批量插入数据
  31. */
  32. @Test
  33. public void AddManyDocument() throws UnknownHostException, JsonProcessingException {
  34. //创建Client连接对象
  35. Settings settings = Settings.builder().put("cluster.name", "my-application").build();
  36. //设置IP地址和端口号
  37. TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
  38. new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
  39.  
  40. ObjectMapper objectMapper=new ObjectMapper();
  41.  
  42. for (int i=1;i<=50;i++) {
  43. Article article = new Article();
  44. //描述json 数据
  45. article.setId(i);
  46. article.setTitle(i + "搜索工作其实很快乐");
  47. article.setContent(i + "我们希望我们的搜索解决方案要快,我们希望有一个零配置和一个完全免费的搜索模式");
  48.  
  49. //创建文档
  50. client.prepareIndex("es_test1", "article", article.getId().toString())
  51. .setSource(objectMapper.writeValueAsString(article).getBytes(),
  52. XContentType.JSON).get();
  53. }
  54.  
  55. //释放资源
  56. client.close();
  57. }
  58. }

2、访问localhost:9100查看

  

3、分页查询

  1. package com.zn.myTest;
  2.  
  3. import com.fasterxml.jackson.core.JsonProcessingException;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import com.zn.entity.Article;
  6. import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
  7. import org.elasticsearch.action.search.SearchRequestBuilder;
  8. import org.elasticsearch.action.search.SearchResponse;
  9. import org.elasticsearch.client.Requests;
  10. import org.elasticsearch.client.transport.TransportClient;
  11. import org.elasticsearch.common.settings.Settings;
  12. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  13. import org.elasticsearch.common.xcontent.XContentBuilder;
  14. import org.elasticsearch.common.xcontent.XContentFactory;
  15. import org.elasticsearch.common.xcontent.XContentType;
  16. import org.elasticsearch.index.query.QueryBuilders;
  17. import org.elasticsearch.search.SearchHit;
  18. import org.elasticsearch.search.SearchHits;
  19. import org.elasticsearch.transport.client.PreBuiltTransportClient;
  20. import org.junit.jupiter.api.Test;
  21.  
  22. import java.io.IOException;
  23. import java.net.InetAddress;
  24. import java.net.UnknownHostException;
  25. import java.util.Iterator;
  26. import java.util.concurrent.ExecutionException;
  27.  
  28. public class MyESTest {
  29.  
  30. /**
  31. * 分页查询
  32. */
  33. @Test
  34. public void selectDocument() throws UnknownHostException {
  35. //创建Client连接对象
  36. Settings settings = Settings.builder().put("cluster.name", "my-application").build();
  37. //设置IP地址和端口号
  38. TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
  39. new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
  40.  
  41. //搜索数据 默认每页10条记录
  42. SearchRequestBuilder searchRequestBuilder = client.prepareSearch("es_test1")
  43. .setTypes("article")
  44. .setQuery(QueryBuilders.matchAllQuery());
  45.  
  46. //从0条开始,每页5条数据
  47. //setFrom():从第几条开始检索,默认是0。
  48. //setSize():每页最多显示的记录数。
  49. searchRequestBuilder.setFrom(0).setSize(5);
  50. SearchResponse searchResponse=searchRequestBuilder.get();
  51.  
  52. //获取命中次数,查询结果有多少对象
  53. SearchHits hits = searchResponse.getHits();
  54. System.out.println("查询结果有:"+hits.getTotalHits()+"条");
  55. //遍历搜索结果数据
  56. Iterator<SearchHit> iterator = hits.iterator();
  57. while (iterator.hasNext()){
  58. //每个查询对象
  59. SearchHit searchHit = iterator.next();
  60. //获取字符串格式打印
  61. System.out.println(searchHit.getSourceAsString());
  62. System.out.println("id:"+searchHit.getSource().get("id"));
  63. System.out.println("title:"+searchHit.getSource().get("title"));
  64. System.out.println("content:"+searchHit.getSource().get("content"));
  65. System.out.println("**************************************************");
  66. }
  67. //释放资源
  68. client.close();
  69. }
  70. }

4、控制台

  

十二、查询结果高亮操作

  在进行关键字搜索时,搜索出的内容中的关键字会显示不同的颜色,称之为高亮 
  ElasticSearch可以对查询出的内容中关键字部分进行标签和样式的设置,但是你需要告诉ElasticSearch使用什么标签对高亮关键字进行包裹 

1、高亮代码

  1. package com.zn.myTest;
  2.  
  3. import com.fasterxml.jackson.core.JsonProcessingException;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import com.zn.entity.Article;
  6. import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
  7. import org.elasticsearch.action.search.SearchRequestBuilder;
  8. import org.elasticsearch.action.search.SearchResponse;
  9. import org.elasticsearch.client.Requests;
  10. import org.elasticsearch.client.transport.TransportClient;
  11. import org.elasticsearch.common.settings.Settings;
  12. import org.elasticsearch.common.text.Text;
  13. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  14. import org.elasticsearch.common.xcontent.XContentBuilder;
  15. import org.elasticsearch.common.xcontent.XContentFactory;
  16. import org.elasticsearch.common.xcontent.XContentType;
  17. import org.elasticsearch.index.query.QueryBuilders;
  18. import org.elasticsearch.search.SearchHit;
  19. import org.elasticsearch.search.SearchHits;
  20. import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
  21. import org.elasticsearch.transport.client.PreBuiltTransportClient;
  22. import org.junit.jupiter.api.Test;
  23.  
  24. import java.io.IOException;
  25. import java.net.InetAddress;
  26. import java.net.UnknownHostException;
  27. import java.util.Iterator;
  28. import java.util.concurrent.ExecutionException;
  29.  
  30. public class MyESTest {
  31.  
  32. /**
  33. * 查询结果高亮操作
  34. */
  35. @Test
  36. public void selectDocumentRed() throws UnknownHostException {
  37. //创建Client连接对象
  38. Settings settings = Settings.builder().put("cluster.name", "my-application").build();
  39. //设置IP地址和端口号
  40. TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
  41. new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
  42.  
  43. //设置搜索条件
  44. SearchRequestBuilder searchRequestBuilder = client.prepareSearch("es_test1")
  45. .setTypes("article")
  46. .setQuery(QueryBuilders.termQuery("title","搜索"));
  47.  
  48. //设置高亮数据
  49. HighlightBuilder highlightBuilder=new HighlightBuilder();
  50. highlightBuilder.preTags("<font style='color:red'>");
  51. highlightBuilder.postTags("</font>");
  52. highlightBuilder.field("title");
  53. searchRequestBuilder.highlighter(highlightBuilder);
  54.  
  55. //获取查询结果数据
  56. SearchResponse searchResponse = searchRequestBuilder.get();
  57.  
  58. //获取查询结果集
  59. SearchHits hits = searchResponse.getHits();
  60. System.out.println("共搜到:"+hits.getTotalHits()+"条数据");
  61. //遍历结果
  62. for (SearchHit hit:hits){
  63. System.out.println("String方式打印文档搜索内容:");
  64. System.out.println(hit.getSourceAsString());
  65. System.out.println("Map方式打印高亮内容");
  66. System.out.println(hit.getHighlightFields());
  67.  
  68. System.out.println("遍历高亮集合,打印高亮片段:");
  69. Text[] text = hit.getHighlightFields().get("title").getFragments();
  70. for (Text str:text){
  71. System.out.println(str);
  72. }
  73. System.out.println("**********************************************************8");
  74. //释放资源
  75. client.close();
  76. }
  77. }
  78. }

2、控制台

  

 

Idea操作ElasticSearch的更多相关文章

  1. 使用curl命令操作elasticsearch

    使用curl命令操作elasticsearch 大岩不灿 发表于 2015年4月25日 浏览 7,426 次 第一:_cat系列_cat系列提供了一系列查询elasticsearch集群状态的接口.你 ...

  2. 使用Java客户端操作elasticsearch(二)

    承接上文,使用Java客户端操作elasticsearch,本文主要介绍 常见的配置 和Sniffer(集群探测) 的使用. 常见的配置 前面已介绍过,RestClientBuilder支持同时提供一 ...

  3. java操作elasticsearch实现组合桶聚合

    1.terms分组查询 //分组聚合 @Test public void test40() throws UnknownHostException{ //1.指定es集群 cluster.name 是 ...

  4. java操作elasticsearch实现query String

    1.CommonTersQuery: 指定字段进行模糊查询 //commonTermsQuery @Test public void test35() throws UnknownHostExcept ...

  5. java操作elasticsearch实现聚合查询

    1.max 最大值 //max 求最大值 @Test public void test30() throws UnknownHostException{ //1.指定es集群 cluster.name ...

  6. java操作elasticsearch实现前缀查询、wildcard、fuzzy模糊查询、ids查询

    1.前缀查询(prefix) //prefix前缀查询 @Test public void test15() throws UnknownHostException { //1.指定es集群 clus ...

  7. java操作elasticsearch实现条件查询(match、multiMatch、term、terms、reange)

    1.条件match query查询 //条件查询match query @Test public void test10() throws UnknownHostException { //1.指定e ...

  8. java操作elasticsearch实现查询删除和查询所有

    后期博客本人都只给出代码,具体的说明在代码中也有注释. 1.查询删除 //查询删除:将查询到的数据进行删除 @Test public void test8() throws UnknownHostEx ...

  9. java操作elasticsearch实现批量添加数据(bulk)

    java操作elasticsearch实现批量添加主要使用了bulk 代码如下: //bulk批量操作(批量添加) @Test public void test7() throws IOExcepti ...

  10. 学习用Node.js和Elasticsearch构建搜索引擎(3):使用curl命令操作elasticsearch

    使用Elasticsearch不免要提到curl工具,curl是利用URL语法在命令行方式下工作的开源文件传输工具.官网地址:https://curl.haxx.se/ 因为elasticsearch ...

随机推荐

  1. vue拦截器

    1.在路由添加 meta:{ requireAuth:true } 完整 { path: '/xx', name: 'xx', component: xx, meta:{ requireAuth:tr ...

  2. kindeditor富文本编译器

    一.网址 kindeditor.net/about.php 二.编辑器的使用,看官方文档 三.常用初始化参数 1.resizeType2或1或0,2时可以拖动改变宽度和高度,1时只能改变高度,0时不能 ...

  3. Codeforces Choosing Laptop 题解

    这题实在是太水了,具体看注释 蒟蒻的方法是一边找过时的电脑一边比大小 蒟蒻不才,只会C++ 其实还会free basic,但它已经过时了 附: 本题洛谷网址 Codeforces网址 希望蒟蒻的题解能 ...

  4. Windows安装Python环境和Python集成开发环境(IDE)PyCharm

    1.Windows中安装Python 3 (1)打开浏览器,访问Python官网(https://www.python.org/) (2)光标移动至Downloads,单机Windows链接 (3)根 ...

  5. (转自360安全客)深入理解浏览器解析机制和XSS向量编码

    (译者注:由于某些词汇翻译成中文后很生硬,因此把相应的英文标注在其后以便理解.这篇文章讲的内容很基础,同时也很重要,希望对大家有所帮助.) 这篇文章将要深入理解HTML.URL和JavaScript的 ...

  6. 解决delete 删除sql语句,标识还保留删除之前的问题

    我有一些数据,想要删除,首先想到的是delete,但是它会保留之前的标识,后来想用truncate来进行删除,但是,它会全部删除,并且不能加条件,只能回过头使用delete,以下是解决delete删除 ...

  7. CSS-04-层叠选择器

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  8. idea中使用Live Template自动生成方法所有参数打印

    一 新建模板 二 设置代码模板 三 设置变量 表达式是支持groovy脚本的,所以这里写一个groovy脚本,生成给定格式的日志字符串,methodParameters()是idea内置的函数,获取方 ...

  9. Jquery 替换全部字符

    item.replace('P','')   只会替换第一个'P'字符 item.replace(/P/gm,'') 替换全部'P'字符

  10. springcloud 依赖版本问题

    SpringCloud 版本: 版本名称 版本 Finchley snapshot版 Edgware snapshot版 Dalston SR1 当前最新稳定版本 Camden SR7 稳定版本 Br ...