Document APIs - Index API

优质
小牛编辑
134浏览
2023-12-01

Index API

Index API 允许我们存储一个JSON格式的文档,使数据可以被搜索。文档通过index、type、id唯一确定。我们可以自己提供一个id,或者也使用Index API 为我们自动生成一个。

这里有几种不同的方式来产生JSON格式的文档(document):

  • 手动方式,使用原生的byte[]或者String
  • 使用Map方式,会自动转换成与之等价的JSON
  • 使用第三方库来序列化beans,如Jackson
  • 使用内置的帮助类 XContentFactory.jsonBuilder()

手动方式

数据格式

  1. String json = "{" +
  2. "\"user\":\"kimchy\"," +
  3. "\"postDate\":\"2013-01-30\"," +
  4. "\"message\":\"trying out Elasticsearch\"" +
  5. "}";
实例
  1. /**
  2. * 手动生成JSON
  3. */
  4. @Test
  5. public void CreateJSON(){
  6. String json = "{" +
  7. "\"user\":\"fendo\"," +
  8. "\"postDate\":\"2013-01-30\"," +
  9. "\"message\":\"Hell word\"" +
  10. "}";
  11. IndexResponse response = client.prepareIndex("fendo", "fendodate")
  12. .setSource(json)
  13. .get();
  14. System.out.println(response.getResult());
  15. }

Map方式

Map是key:value数据类型,可以代表json结构.

  1. Map<String, Object> json = new HashMap<String, Object>();
  2. json.put("user","kimchy");
  3. json.put("postDate",new Date());
  4. json.put("message","trying out Elasticsearch");
实例
  1. /**
  2. * 使用集合
  3. */
  4. @Test
  5. public void CreateList(){
  6. Map<String, Object> json = new HashMap<String, Object>();
  7. json.put("user","kimchy");
  8. json.put("postDate","2013-01-30");
  9. json.put("message","trying out Elasticsearch");
  10. IndexResponse response = client.prepareIndex("fendo", "fendodate")
  11. .setSource(json)
  12. .get();
  13. System.out.println(response.getResult());
  14. }

序列化方式

ElasticSearch已经使用了jackson,可以直接使用它把javabean转为json.

  1. import com.fasterxml.jackson.databind.*;
  2. // instance a json mapper
  3. ObjectMapper mapper = new ObjectMapper(); // create once, reuse
  4. // generate json
  5. byte[] json = mapper.writeValueAsBytes(yourbeaninstance);
实例
  1. /**
  2. * 使用JACKSON序列化
  3. * @throws Exception
  4. */
  5. @Test
  6. public void CreateJACKSON() throws Exception{
  7. CsdnBlog csdn=new CsdnBlog();
  8. csdn.setAuthor("fendo");
  9. csdn.setContent("这是JAVA书籍");
  10. csdn.setTag("C");
  11. csdn.setView("100");
  12. csdn.setTitile("编程");
  13. csdn.setDate(new Date().toString());
  14. // instance a json mapper
  15. ObjectMapper mapper = new ObjectMapper(); // create once, reuse
  16. // generate json
  17. byte[] json = mapper.writeValueAsBytes(csdn);
  18. IndexResponse response = client.prepareIndex("fendo", "fendodate")
  19. .setSource(json)
  20. .get();
  21. System.out.println(response.getResult());
  22. }

XContentBuilder帮助类方式

ElasticSearch提供了一个内置的帮助类XContentBuilder来产生JSON文档

  1. // Index name
  2. String _index = response.getIndex();
  3. // Type name
  4. String _type = response.getType();
  5. // Document ID (generated or not)
  6. String _id = response.getId();
  7. // Version (if it's the first time you index this document, you will get: 1)
  8. long _version = response.getVersion();
  9. // status has stored current instance statement.
  10. RestStatus status = response.status();
实例
  1. /**
  2. * 使用ElasticSearch 帮助类
  3. * @throws IOException
  4. */
  5. @Test
  6. public void CreateXContentBuilder() throws IOException{
  7. XContentBuilder builder = XContentFactory.jsonBuilder()
  8. .startObject()
  9. .field("user", "ccse")
  10. .field("postDate", new Date())
  11. .field("message", "this is Elasticsearch")
  12. .endObject();
  13. IndexResponse response = client.prepareIndex("fendo", "fendodata").setSource(builder).get();
  14. System.out.println("创建成功!");
  15. }

综合实例

  1. import java.io.IOException;
  2. import java.net.InetAddress;
  3. import java.net.UnknownHostException;
  4. import java.util.Date;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. import org.elasticsearch.action.index.IndexResponse;
  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.transport.client.PreBuiltTransportClient;
  14. import org.junit.Before;
  15. import org.junit.Test;
  16. import com.fasterxml.jackson.core.JsonProcessingException;
  17. import com.fasterxml.jackson.databind.ObjectMapper;
  18. public class CreateIndex {
  19. private TransportClient client;
  20. @Before
  21. public void getClient() throws Exception{
  22. //设置集群名称
  23. Settings settings = Settings.builder().put("cluster.name", "my-application").build();// 集群名
  24. //创建client
  25. client = new PreBuiltTransportClient(settings)
  26. .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
  27. }
  28. /**
  29. * 手动生成JSON
  30. */
  31. @Test
  32. public void CreateJSON(){
  33. String json = "{" +
  34. "\"user\":\"fendo\"," +
  35. "\"postDate\":\"2013-01-30\"," +
  36. "\"message\":\"Hell word\"" +
  37. "}";
  38. IndexResponse response = client.prepareIndex("fendo", "fendodate")
  39. .setSource(json)
  40. .get();
  41. System.out.println(response.getResult());
  42. }
  43. /**
  44. * 使用集合
  45. */
  46. @Test
  47. public void CreateList(){
  48. Map<String, Object> json = new HashMap<String, Object>();
  49. json.put("user","kimchy");
  50. json.put("postDate","2013-01-30");
  51. json.put("message","trying out Elasticsearch");
  52. IndexResponse response = client.prepareIndex("fendo", "fendodate")
  53. .setSource(json)
  54. .get();
  55. System.out.println(response.getResult());
  56. }
  57. /**
  58. * 使用JACKSON序列化
  59. * @throws Exception
  60. */
  61. @Test
  62. public void CreateJACKSON() throws Exception{
  63. CsdnBlog csdn=new CsdnBlog();
  64. csdn.setAuthor("fendo");
  65. csdn.setContent("这是JAVA书籍");
  66. csdn.setTag("C");
  67. csdn.setView("100");
  68. csdn.setTitile("编程");
  69. csdn.setDate(new Date().toString());
  70. // instance a json mapper
  71. ObjectMapper mapper = new ObjectMapper(); // create once, reuse
  72. // generate json
  73. byte[] json = mapper.writeValueAsBytes(csdn);
  74. IndexResponse response = client.prepareIndex("fendo", "fendodate")
  75. .setSource(json)
  76. .get();
  77. System.out.println(response.getResult());
  78. }
  79. /**
  80. * 使用ElasticSearch 帮助类
  81. * @throws IOException
  82. */
  83. @Test
  84. public void CreateXContentBuilder() throws IOException{
  85. XContentBuilder builder = XContentFactory.jsonBuilder()
  86. .startObject()
  87. .field("user", "ccse")
  88. .field("postDate", new Date())
  89. .field("message", "this is Elasticsearch")
  90. .endObject();
  91. IndexResponse response = client.prepareIndex("fendo", "fendodata").setSource(builder).get();
  92. System.out.println("创建成功!");
  93. }
  94. }

你还可以通过startArray(string)和endArray()方法添加数组。.field()方法可以接受多种对象类型。你可以给它传递数字、日期、甚至其他XContentBuilder对象。