当前位置: 移动技术网 > IT编程>开发语言>Java > java使用es查询的示例代码

java使用es查询的示例代码

2019年07月19日  | 移动技术网IT编程  | 我要评论

众所周知,elasticsearch简称es,它是基于基于lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于restful web接口。elasticsearch是用java开发的,并作为apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。

我们建立一个网站或应用程序,并要添加搜索功能,但是想要完成搜索工作的创建是非常困难的。我们希望搜索解决方案要运行速度快,我们希望能有一个零配置和一个完全免费的搜索模式,我们希望能够简单地使用json通过http来索引数据,我们希望我们的搜索服务器始终可用,我们希望能够从一台开始并扩展到数百台,我们要实时搜索,我们要简单的多租户,我们希望建立一个云的解决方案。因此我们利用elasticsearch来解决所有这些问题以及可能出现的更多其它问题。

在java中使用es时,无非想解决的是查询速度不够快,效率不够高问题,单一从数据库里查询数据已经不能拿满足当前的业务需求,ok!那么现在我们来讲述一下如何在java中使用到es这个神奇的搜索服务器呢,首先,你得要去引用es的依赖包,依赖如下:

<dependency>
<groupid>org.elasticsearch.client</groupid>
<artifactid>transport</artifactid>
<version>5.5.0</version>
  </dependency>
<groupid>org.elasticsearch.client</groupid>
<artifactid>transport</artifactid>
<version>5.5.0</version>
  </dependency>
     <dependency>
<groupid>org.elasticsearch</groupid>
<artifactid>elasticsearch</artifactid>
<version>5.5.0</version>
 </dependency>

好的,添加完依赖之后,进入到es使用阶段,对了,有个问题得需要说明一下,要使用es的话需要安装jdk1.8工具包并且tomcat最好是7.05以上的版本,不然es会不支持,集成到项目里面可能会报错!,还有es的安装和下载,这里附下载地址下载地址:

一切准备就绪后接下来进入到我们真正期待的时刻,什么呢,没错,集成es,究竟如何在java里面搜索查询es服务器里面的东西呢,让我一一来为你揭晓:

首先我们建议一个es的工具类

package com.osa.utils;
import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstreamreader;
import java.io.printwriter;
import java.net.url;
import java.net.urlconnection;
import java.net.urlencoder;
import java.util.iterator;
import java.util.list;
import java.util.map;
import java.util.set;
import org.apache.http.client.clientprotocolexception;
import com.alibaba.fastjson.jsonarray;
import com.alibaba.fastjson.jsonexception;
import com.alibaba.fastjson.jsonobject;

public class httpsentutils {
/**
  * 向指定url发送get方法的请求
  * 
  * @param url
  *   发送请求的url
  * @param param
  *   请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  * @return url 所代表远程资源的响应结果
  */
 public static string sendget(string url, string param) {
  string result = "";
  bufferedreader in = null;
  try {
   string urlnamestring = url + "?" + param;
   url realurl = new url(urlnamestring);
   // 打开和url之间的连接
   urlconnection connection = realurl.openconnection();
   // 设置通用的请求属性
   connection.setrequestproperty("accept", "*/*");
   connection.setrequestproperty("connection", "keep-alive");
   connection.setrequestproperty("user-agent",
     "mozilla/4.0 (compatible; msie 6.0; windows nt 5.1;sv1)");
   // 建立实际的连接
   connection.connect();
   // 获取所有响应头字段
   map<string, list<string>> map = connection.getheaderfields();
   // 遍历所有的响应头字段
   for (string key : map.keyset()) {
    system.out.println(key + "--->" + map.get(key));
   }
   // 定义 bufferedreader输入流来读取url的响应
   in = new bufferedreader(new inputstreamreader(
     connection.getinputstream()));
   string line;
   while ((line = in.readline()) != null) {
    result += line;
   }
  } catch (exception e) {
   system.out.println("发送get请求出现异常!" + e);
   e.printstacktrace();
  }
  // 使用finally块来关闭输入流
  finally {
   try {
    if (in != null) {
     in.close();
    }
   } catch (exception e2) {
    e2.printstacktrace();
   }
  }
  return result;
 }
 /**
  * 向指定 url 发送post方法的请求
  * 
  * @param url
  *   发送请求的 url
  * @param param
  *   请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  * @return 所代表远程资源的响应结果
  */
 public static string sendpost(string url, string param) {
  printwriter out = null;
  bufferedreader in = null;
  string result = "";
  try {
   url realurl = new url(url);
   // 打开和url之间的连接
   urlconnection conn = realurl.openconnection();
   // 设置通用的请求属性
   conn.setrequestproperty("accept", "*/*");
   conn.setrequestproperty("connection", "keep-alive");
   conn.setrequestproperty("user-agent",
     "mozilla/4.0 (compatible; msie 6.0; windows nt 5.1;sv1)");
   // 发送post请求必须设置如下两行
   conn.setdooutput(true);
   conn.setdoinput(true);
   // 获取urlconnection对象对应的输出流
   out = new printwriter(conn.getoutputstream());
   // 发送请求参数
   out.print(param);
   // flush输出流的缓冲
   out.flush();
   // 定义bufferedreader输入流来读取url的响应
   in = new bufferedreader(
     new inputstreamreader(conn.getinputstream()));
   string line;
   while ((line = in.readline()) != null) {
    result += line;
   }
  } catch (exception e) {
   system.out.println("发送 post 请求出现异常!"+e);
   e.printstacktrace();
  }
  //使用finally块来关闭输出流、输入流
  finally{
   try{
    if(out!=null){
     out.close();
    }
    if(in!=null){
     in.close();
    }
   }
   catch(ioexception ex){
    ex.printstacktrace();
   }
  }
  return result;
 } 
}

工具类有了之后,可以看到里面有两个发送请求的方法,一个是sendget和sendpost方法,两个方法可以基于自己的选择选用,当然这只是个发送请求的方法,如何调用?在这里的话,我们既然是从es里面查询,就没有必要使用mybatis或者hibernate框架了,可以在数据层中,自己定义sql,然后将sql将拼好的sql通过前面的工具类调用sendget/sendpost方法,如下:

string sql=urlencoder.encode(" select * from table");encode方法主要是去除sql里面的一些空格

string result=httpsentutils.sendget("http://221.124.71.8:9200/_sql", "sql="+sql);ip加端口自己可以在安装的时候配置

ok!一般到这个时候的发送可以成功的话,就能取到es里面的数据,因为es里面返回的都是json数据,所以我们
格式化一下json字符串

net.sf.json.jsonobject jsonobject =net.sf.json.jsonobject.fromobject(result); 
//取出hits标签
net.sf.json.jsonobject hitsjsonobject = jsonobject.getjsonobject("hits");

数据拿到之后,结下来就是业务操作了。到这里也差不多结束了。

以上是查询的一些操作,那么如果我们需要将数据批量插入到es里面该如何操作?举个例子吧

package com.sojson.core.elasticsearch.manager;
import java.util.arraylist;
import java.util.hashmap;
import java.util.list;
import java.util.map;
import net.sf.json.jsonobject;
import org.elasticsearch.action.bulk.bulkrequestbuilder;
import org.elasticsearch.action.bulk.bulkresponse;
import org.elasticsearch.action.index.indexrequestbuilder;
import com.sojson.common.utils.stringutils;
import com.sojson.core.elasticsearch.utils.estools;
publicclassinsertmanager{
/**
* 添加数据到elasticsearch
*@param index 索引
*@param type 类型
*@param idname id字段名称
*@param json 存储的json,可以接受map
*@return
*/
publicstaticmapsave(string index,string type,string idname,jsonobject json){
list list =newarraylist();
list.add(json);
return save(index, type, idname, list);
}

通过传来的参数进行处理调用save方法执行插入es操作

/**
* 添加数据到elasticsearch
*@param index 索引
*@param type 类型
*@param idname id字段名称
*@param listdata 一个对象集合
*@return
*/
@suppresswarnings("unchecked")
publicstaticmapsave(string index,string type,string idname,list listdata){
bulkrequestbuilder bulkrequest =estools.client.preparebulk().setrefresh(true);
map resultmap =newhashmap();
for(object object: listdata){
jsonobject json =jsonobject.fromobject(object);
//没有指定idname 那就让elasticsearch自动生成,
if(stringutils.isblank(idname)){
indexrequestbuilder lrb =elasticsearchutils.client
               .prepareindex(index, type)
                .setsource(json);
bulkrequest.add(lrb);
//elasticsearchutils是工具类,里面配置的是一些es配置信息
}
else{
string idvalue = json.optstring(idname);
indexrequestbuilder lrb =estools.client.prepareindex(index, type,idvalue).setsource(json);
bulkrequest.add(lrb);
}
}
bulkresponse bulkresponse = bulkrequest.execute().actionget();
if(bulkresponse.hasfailures()){
// process failures by iterating through each bulk response item
system.out.println(bulkresponse.getitems().tostring());
resultmap.put("500","保存es失败!");
return resultmap;
}
bulkrequest=estools.client.preparebulk();
resultmap.put("200","保存es成功!");
return resultmap;
}
}

elasticsearchutils工具类

public class elasticsearchutils {
private static final string cluster_name = "cluster.name";
private static final string es_ip="es.ip";
private static final string es_port="es.port";

private static settings settings;
private static transportclient client;
public static transportclient getesclient() throws unknownhostexception{
settings = settings.builder().put(cluster_name,configutils.getconfig(cluster_name)).build();
if(client != null){
client = new prebuilttransportclient(settings).addtransportaddress(new inetsockettransportaddress(inetaddress.getbyname(configutils.getconfig(es_ip)), integer.parseint(configutils.getconfig(es_port))));
}
return client;
}

以上是插入es操作,好了,今天的总结就到这里吧,希望可以给大家带来一些小小的帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网