一、生成JSON
四种方式如下,官网文档:https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs-index.html:
**1.1手写方式生成
**
String json = "{" +
""user":"fendo"," +
""postDate":"2013-01-30"," +
""message":"Hell word"" +
"}";
**1.2使用集合
**
集合是key:value数据类型,可以代表json结构.
Map<String, Object> json = new HashMap<String, Object>();
json.put("user","kimchy");
json.put("postDate","2013-01-30");
json.put("message","trying out Elasticsearch");
**1.3使用JACKSON序列化
**
ElasticSearch已经使用了jackson,可以直接使用它把javabean转为json.
// instance a json mapper
ObjectMapper mapper = new ObjectMapper(); // create once, reuse
// generate json
byte[] json = mapper.writeValueAsBytes(yourbeaninstance);
1.4使用ElasticSearch 帮助类
XContentBuilder builder = jsonBuilder()
.startObject()
.field("user", "kimchy")
.field("postDate", new Date())
.field("message", "trying out Elasticsearch")
.endObject()
String json = builder.string();
完整示例:
package com.fendo.temp;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Before;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class CreateIndex {
private TransportClient client;
@Before
public void getClient() throws Exception{
//设置集群名称
Settings settings = Settings.builder().put("cluster.name", "my-application").build();// 集群名
//创建client
client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
}
/**
* 手动生成JSON
*/
@Test
public void CreateJSON(){
String json = "{" +
""user":"fendo"," +
""postDate":"2013-01-30"," +
""message":"Hell word"" +
"}";
IndexResponse response = client.prepareIndex("fendo", "fendodate")
.setSource(json)
.get();
System.out.println(response.getResult());
}
/**
* 使用集合
*/
@Test
public void CreateList(){
Map<String, Object> json = new HashMap<String, Object>();
json.put("user","kimchy");
json.put("postDate","2013-01-30");
json.put("message","trying out Elasticsearch");
IndexResponse response = client.prepareIndex("fendo", "fendodate")
.setSource(json)
.get();
System.out.println(response.getResult());
}
/**
* 使用JACKSON序列化
* @throws Exception
*/
@Test
public void CreateJACKSON() throws Exception{
CsdnBlog csdn=new CsdnBlog();
csdn.setAuthor("fendo");
csdn.setContent("这是JAVA书籍");
csdn.setTag("C");
csdn.setView("100");
csdn.setTitile("编程");
csdn.setDate(new Date().toString());
// instance a json mapper
ObjectMapper mapper = new ObjectMapper(); // create once, reuse
// generate json
byte[] json = mapper.writeValueAsBytes(csdn);
IndexResponse response = client.prepareIndex("fendo", "fendodate")
.setSource(json)
.get();
System.out.println(response.getResult());
}
/**
* 使用ElasticSearch 帮助类
* @throws IOException
*/
@Test
public void CreateXContentBuilder() throws IOException{
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.field("user", "ccse")
.field("postDate", new Date())
.field("message", "this is Elasticsearch")
.endObject();
IndexResponse response = client.prepareIndex("fendo", "fendodata").setSource(builder).get();
System.out.println("创建成功!");
}
}
二、解析JSON
Jest对获取的JSON数据,有两种解析方式
1、手动解析文章来源:https://www.toymoban.com/news/detail-509179.html
/**
* 手动解析
* @throws IOException
*/
@Test
public void ManualOperation() throws IOException{
int pageNumber=1;
int pageSize=10;
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.queryStringQuery("JAVA"));
searchSourceBuilder.from((pageNumber - 1) * pageSize);//设置起始页
searchSourceBuilder.size(pageSize);//设置页大小
Search search = new Search.Builder(searchSourceBuilder.toString())
.addIndex(indexName)// 索引名称
.build();
SearchResult result = jestClient.execute(search);
// 手动解析
JsonObject jsonObject = result.getJsonObject();
JsonObject hitsobject = jsonObject.getAsJsonObject("hits");
long took = jsonObject.get("took").getAsLong();
long total = hitsobject.get("total").getAsLong();
JsonArray jsonArray = hitsobject.getAsJsonArray("hits");
System.out.println("took:"+took+" "+"total:"+total);
List<CsdnBlog> csdnBlogs=new ArrayList<CsdnBlog>();
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject jsonHitsObject = jsonArray.get(i).getAsJsonObject();
// 获取返回字段
JsonObject sourceObject = jsonHitsObject.get("_source").getAsJsonObject();
// 封装Article对象
CsdnBlog article = new CsdnBlog();
article.setTitile(sourceObject.get("titile").getAsString());
article.setContent(sourceObject.get("content").getAsString());
article.setAuthor(sourceObject.get("author").getAsString());
article.setDate(sourceObject.get("date").getAsString());
article.setTag(sourceObject.get("tag").getAsString());
article.setView(sourceObject.get("view").getAsString());
csdnBlogs.add(article);
}
System.out.println(csdnBlogs.size());
}
2、自动解析:文章来源地址https://www.toymoban.com/news/detail-509179.html
/**
* 自动解析
* @throws Exception
*/
@Test
public void Auto() throws Exception{
int pageNumber=1;
int pageSize=10;
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.queryStringQuery("JAVA"));
searchSourceBuilder.from((pageNumber - 1) * pageSize);//设置起始页
searchSourceBuilder.size(pageSize);//设置页大小
Search search = new Search.Builder(searchSourceBuilder.toString())
.addIndex(indexName)// 索引名称
.build();
SearchResult result = jestClient.execute(search);
// 自动解析
JsonObject jsonObject = result.getJsonObject();
JsonObject hitsobject = jsonObject.getAsJsonObject("hits");
long took = jsonObject.get("took").getAsLong();
long total = hitsobject.get("total").getAsLong();
System.out.println("took:"+took+" "+"total:"+total);
List<SearchResult.Hit<CsdnBlog, Void>> hits = result.getHits(CsdnBlog.class);
List<CsdnBlog> csdnBlogs=new ArrayList<CsdnBlog>();
for (SearchResult.Hit<CsdnBlog, Void> hit : hits) {
CsdnBlog source = hit.source;
csdnBlogs.add(source);
}
System.out.println(csdnBlogs.size());
}
到了这里,关于Elasticsearch系列(八)----ES生成JSON与解析JSON的方式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!