使用Java Low Level REST Client封装一个查询与返回

目录

Java REST客户端有两种风格:

1.为什么不使用Transport 客户端进行开发?

2.为什么不使用高级rest 客户端开发?

         3.自己动手封装一个高亮查询与返回

                     1.创建 restClient 客户端

                     2.简单的执行请求

                     3.封装一个查询

          参考资料:


Java REST客户端有两种风格:

Java低级别REST客户端(Java Low Level REST Client,以后都简称低级客户端算了,难得码字):Elasticsearch的官方low-level客户端。 它允许通过http与Elasticsearch集群进行通信。 不会对请求进行编码和响应解码。 它与所有Elasticsearch版本兼容。
Java高级REST客户端(Java High Level REST Client,以后都简称高级客户端):Elasticsearch的官方high-level客户端。 基于low-level客户端,它公开了API特定的方法,并负责处理。

1.为什么不使用Transport 客户端进行开发?

地址:https://m.aliyun.com/doc/document_detail/69194.html

官方已经不建议使用Transport 客户端来访问elasticSearch 服务器

2.为什么不使用高级rest 客户端开发

由于项目需要,高级rest客户端与当前的elasticSearch服务器版本不能完美的兼容,

连接时候会报出一些问题,阿里的官方也推荐使用低版本的客户端 进行原生的http请求

那么就自己封装了一个低版本的客户端进行 查询 与返回

3.自己动手封装一个高亮查询与返回

maven坐标:



<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-client</artifactId>
    <version>6.2.3</version>
</dependency>

1.创建 restClient 客户端

EsUtils工具类中

	public static RestClient getRestClient() {
			RestClientBuilder builder = RestClient.builder(new HttpHost("127.0.0.1",9200, "http"));
		RestClient restClient = builder.build();
		return restClient;
	}

2.简单的执行请求

GET /_search
{
  "profile": true,
  "query" : {
    "match" : { "message" : "message number" }
  }
}

原生的http请求elasticSearch

那么在restClient风格中的请求格式为

RestClient restClient = EsUtils.getRestClient();
		String method = "POST";
		String endpoint = "/rupeng//_count?pretty";
		HttpEntity entity = new NStringEntity("{\n" + "  \"query\": {\n" + "    \"match_all\": {}\n" + "  }\n" + "}",
				ContentType.APPLICATION_JSON);
		Response response;
		try {
			response = restClient.performRequest(method, endpoint, Collections.<String, String> emptyMap(), entity);
			System.out.println(EntityUtils.toString(response.getEntity()));

		} catch (IOException e) {
			logger.error(e);
			throw new RuntimeException(e);
		} finally {
			try {
				restClient.close();
			} catch (IOException e) {
				logger.error(e);
			}
		}

3.封装一个查询

可以发现 我们请求的数据格式都是json的数据格式,那么为了避免 每次请求都去拼接一个 查询 ,我们完全可以将它定义成为一个对象,再使用gson等转换工具将对象转换为json字符串,这样就避免了复杂的拼接以及提高了程序的可扩展性与避免一些不必要的错误,返回数据的格式也为json格式,需要我们将数据转换为对象。

那么接下来 我们就来封装一个高亮查询与返回

	"query": {
		"multi_match": {
			"query": "测试",
			"fields": ["body", "title"]
		}
	},
	"highlight": {
		"fields": {
			"title": {
				"pre_tags": "<span style=\"color:red\">",
				"post_tags": "</span>"
			},
			"body": {
				"pre_tags": "<span style=\"color:red\">",
				"post_tags": "</span>"
			}
		}
	},
	"from": 0,
	"size": 20
}

对该查询进行一次封装,其中fields 为查询的属性为title 和body,highlight为高亮查询 ,查询的结果会拼接pre_tags pro_tags这个标签.size为查询返回数据的大小,from从哪里开始。目录图

需要创建的类如图所示

Root 类


/**
 * 
 * @author 2016wlw2 徐塬峰 创建时间:2018年8月2日 上午11:51:43
 */
public class Root {
	public Query query;
	public Highlight highlight;
	public int from = 0;// 默认值
	public int size = 10000;// 默认值

	public Query getQuery() {
		return query;
	}

	public void setQuery(Query query) {
		this.query = query;
	}

	public int getFrom() {
		return from;
	}

	public void setFrom(int from) {
		this.from = from;
	}

	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}

	public Highlight getHighlight() {
		return highlight;
	}

	public void setHighlight(Highlight highlight) {
		this.highlight = highlight;
	}

	@Override
	public String toString() {
		return "Root [query=" + query + ", from=" + from + ", size=" + size + "]";
	}

}

Query类

public class Query {

	private Multi_match multi_match;
	private Match_all match_all;
	private Type type;
	   
	
    public void setMatch_all(Match_all match_all) {
         this.match_all = match_all;
     }
     public Match_all getMatch_all() {
         return match_all;
     }
	public Multi_match getMulti_match() {
		return multi_match;
	}

	public void setMulti_match(Multi_match multi_match) {
		this.multi_match = multi_match;
	}
	public void setType(Type type) {
         this.type = type;
     }
	 
	 
	 
	@Override
	public String toString() {
		return "Query [multi_match=" + multi_match + "]";
	}

multi类

public class Multi_match {
	public String query;

	public List<String> fields;

	public String getQuery() {
		return query;
	}

	public void setQuery(String query) {
		this.query = query;
	}

	public List<String> getFields() {
		return fields;
	}

	public void setFields(List<String> fields) {
		this.fields = fields;
	}

	@Override
	public String toString() {
		return "Multi_match [query=" + query + ", fields=" + fields + "]";
	}

highlight类

	public Fields fields;

	@Override
	public String toString() {
		return "Highlight [fields=" + fields + "]";
	}

	public Fields getFields() {
		return fields;
	}

	public void setFields(Fields fields) {
		this.fields = fields;
	}

fields高亮类

/**
 * 设置高亮字段
 * @author 2016wlw2 徐塬峰
 * 创建时间:2018年8月2日 下午2:53:30
 */
public class Fields {
	public Title title;
    public Body body;
    
	
	
	public Body getBody() {
		return body;
	}

	public void setBody(Body body) {
		this.body = body;
	}

	public Title getTitle() {
		return title;
	}

	public void setTitle(Title title) {
		this.title = title;
	}

	@Override
	public String toString() {
		return "Fields [title=" + title + "]";
	}

Body类

private String pre_tags;
    private String post_tags;
    
    
	public String getPre_tags() {
		return pre_tags;
	}
	public void setPre_tags(String pre_tags) {
		this.pre_tags = pre_tags;
	}
	public String getPost_tags() {
		return post_tags;
	}
	public void setPost_tags(String post_tags) {
		this.post_tags = post_tags;
	}
	@Override
	public String toString() {
		return "Body [pre_tags=" + pre_tags + ", post_tags=" + post_tags + "]";
	}
    

Title类

	public String pre_tags;
	///
	/// </summary>
	public String post_tags;

	public String getPre_tags() {
		return pre_tags;
	}

	public void setPre_tags(String pre_tags) {
		this.pre_tags = pre_tags;
	}

	public String getPost_tags() {
		return post_tags;
	}

	public void setPost_tags(String post_tags) {
		this.post_tags = post_tags;
	}

	@Override
	public String toString() {
		return "Titile [pre_tags=" + pre_tags + ", post_tags=" + post_tags + "]";
	}

Type类

	
	    private String value;
	    public void setValue(String value) {
	         this.value = value;
	     }
	     public String getValue() {
	         return value;
	     }
	

如何使用程序来构建一个高亮查询

                Title title = new Title();
		Body body = new Body();
		body.setPre_tags("<span style=\"color:red\">");
		body.setPost_tags("</span>");
		title.setPre_tags("<span style=\"color:red\">");
		title.setPost_tags("</span>");// 結束
		Fields field = new Fields();
		field.setTitle(title);
		field.setBody(body);

		Highlight highlight = new Highlight();
		highlight.setFields(field);

		// 需要構建返回高亮的字段
		Root root = new Root();
		root.setQuery(query);
		root.setHighlight(highlight);
		int pageSize = 20;
		int startSize = (current - 1) * 20;// 起点
		root.setFrom(startSize);// 分页代码 设置起始位置
		root.setSize(pageSize);// 设置返回的size 大小

使用gson转换为json对象

			HttpEntity entity = new NStringEntity(gson.toJson(root), ContentType.APPLICATION_JSON);
Response response = restClient.performRequest(method, endpoint, Collections.<String, String> emptyMap(), entity);	
JsonRootBean result = gson.fromJson(EntityUtils.toString(response.getEntity()), JsonRootBean.class);

返还一个JsonRootBean对象

JsonRootBean的构建方法与Root相同 这里就不一一列举了。

关于TransPort的查询可以参考这篇文章:https://blog.csdn.net/RAVEEE/article/details/80063320

参考资料:

https://artifacts.elastic.co/javadoc/org/elasticsearch/client/elasticsearch-rest-client/6.2.2/index.html

https://www.cnblogs.com/ginb/p/8682092.html

https://m.aliyun.com/doc/document_detail/69194.html

猜你喜欢

转载自blog.csdn.net/RAVEEE/article/details/81407014