本文共 2791 字,大约阅读时间需要 9 分钟。
本文主要向大家介绍了Oracle数据库之java 从Oracle数据库到处数据到Elasticsearch全文检索库进行全文查询,通过具体的内容向大家展现,希望对大家学习Oracle数据库有所帮助。
首先编写代码前,要先把Elasticsearch环境搭建好(这个很简单,网上百度一大堆)。然后将elasticsearch jar包导入工程当中。
之后开始编码工作:
第一步:编写连接本地Elasticsearch环境的代码
public static Client client=null;
public static Client getClient(){
if(client !=null){
return client;
}
Settings settings = Settings.settingsBuilder().put("cluster.name","my-application").build();
try{
client = TransportClient.builder().settings(settings).build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(null),9300));//如果是Null,则默认连接本地Ip
}catch(UnknownHostException e){
e.printStackTrace();
}
return client;
}
第二步,建立索引库和创建索引
public void createIndexResponse(String indexname, String type, Listjsondata){
//创建索引库 需要注意的是.setRefresh(true)这里一定要设置,否则第一次建立索引查找不到数据
IndexRequestBuilder requestBuilder = getClient().prepareIndex(indexname, type).setRefresh(true);
for(int i=0; i
requestBuilder.setSource(jsondata.get(i)).execute().actionGet();
}
}
/**
* 创建索引
* @param client
* @param jsondata
* @return
*/
public IndexResponse createIndexResponse(String indexname, String type,String jsondata){
IndexResponse response = getClient().prepareIndex(indexname, type)
.setSource(jsondata)
.execute()
.actionGet();
return response;
}
/**
* 执行搜索
* @param queryBuilder
* @param indexname
* @param type
* @return
*/
public Listsearcher(QueryBuilder queryBuilder, String indexname, String type){
Listlist = new ArrayList();//EsBean是数据库的字段
SearchResponse searchResponse = getClient().prepareSearch(indexname).setTypes(type)
.setQuery(queryBuilder)
.execute()
.actionGet();
SearchHits hits = searchResponse.getHits();
System.out.println("查询到记录数=" + hits.getTotalHits());
SearchHit[] searchHists = hits.getHits();
if(searchHists.length>0){
for(SearchHit hit:searchHists){
Integer id = (Integer)hit.getSource().get("id");
String name = (String) hit.getSource().get("name");
String function = (String) hit.getSource().get("funciton");
list.add(new EsBean(id, name, function));
}
}
return list;
}
第三步,写入实体类Esbean
public class Esbean{
private String reg_id;
private String organization;
省略setter和getter方法;
public EsBean(String reg_id,String organization){
super();
this.reg_id=reg_id;
this.organization=organization;
}
}
第四步,从oracle数据库中查询出数据导入到Esalticsearch库中
1 public class jdbc{
2 public static jdbc dataFactory = new jdbc();
3 private static Connection conn;
4 static final String username="****";
5 static final String password="*****";
6 static final String url="***********";
7 public static synchronized Connection getInstance(){
8 if(conn=null || conn.isClosed()){
9 class.forName("oracle.jdbc.driver.OracleDriver");
10 conn=DriverManager.getConnection(url,username,password);
11 }
12 return conn;
13 }
14 }
本文由职坐标整理并发布,希望对同学们学习Oracle有所帮助,更多内容请关注职坐标数据库Oracle数据库频道!
转载地址:http://xcima.baihongyu.com/