Elasticsearch系列(八)----ES生成JSON与解析JSON的方式

一、生成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 json = new HashMap();
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 json = new HashMap();
		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、手动解析


   /**
     * 手动解析
     * @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 csdnBlogs=new ArrayList(); 
        
        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、自动解析:


   /**
     * 自动解析
     * @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> hits = result.getHits(CsdnBlog.class);
        
        List csdnBlogs=new ArrayList(); 
        for (SearchResult.Hit hit : hits) {
        	
        	CsdnBlog source = hit.source;
        	csdnBlogs.add(source);
        	
        }
        System.out.println(csdnBlogs.size());
        
    }


你可能感兴趣的:(Elasticsearch)