设为首页 收藏本站
查看: 986|回复: 0

[经验分享] elasticsearch java调用实例

[复制链接]

尚未签到

发表于 2017-5-20 11:19:43 | 显示全部楼层 |阅读模式
http://outofmemory.cn/code-snippet/3780/Java-Client-call-ElasticSearch-do-quanwen-search-code-example

package com.es;
import java.io.IOException;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentFactory;
public class Test {
public static void main(String[] args) throws ElasticsearchException, IOException {
Settings settings = ImmutableSettings.settingsBuilder().put("client.transport.sniff", true).put("cluster.name", "elasticsearch_useraudit").build();  
Client client = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress("192.168.41.128", 9301));  
IndexResponse response = client.prepareIndex("comment_index", "comment_ugc", "comment_123674")  
.setSource( XContentFactory.jsonBuilder()  
.startObject()  
.field("author", "569874")  
.field("author_name", "riching")  
.field("mark", 232)  
.field("body", "北京不错,但是人太多了")  
.field("createDate", "20130801175520")  
.field("valid", true)  
.endObject())  
.setTTL(8000)  
.execute().actionGet();  
System.out.println(response.getId());  
}
}


另外一个例子:

package com.es;
import java.util.ArrayList;
import java.util.List;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
/**
*
*
*  @version : 1.0
*  
*  @author  : 苏若年              <a href="mailto:DennisIT@163.com">发送邮件</a>
*   
*  @since   : 1.0        创建时间:    2013-4-8    上午11:34:04
*     
*  @function: TODO        
*
*/
public class ElasticSearchHandler {
private Client client;
public ElasticSearchHandler(){   
//使用本机做为节点
this("192.168.41.128");
}
public ElasticSearchHandler(String ipAddress){
//集群连接超时设置
/*  
Settings settings = ImmutableSettings.settingsBuilder().put("client.transport.ping_timeout", "10s").build();
client = new TransportClient(settings);
*/
//        client = new TransportClient().addTransportAddress(new InetSocketTransportAddress("192.168.41.128", 9301));
Settings settings = ImmutableSettings.settingsBuilder().put("client.transport.sniff", true).put("cluster.name", "elasticsearch_useraudit").build();  
client = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress("192.168.41.128", 9301));  
}

/**
* 建立索引,索引建立好之后,会在elasticsearch-0.20.6\data\elasticsearch\nodes\0创建所以你看
* @param indexName  为索引库名,一个es集群中可以有多个索引库。 名称必须为小写
* @param indexType  Type为索引类型,是用来区分同索引库下不同类型的数据的,一个索引库下可以有多个索引类型。
* @param jsondata     json格式的数据集合
*
* @return
*/
public void createIndexResponse(String indexname, String type, List<String> jsondata){
//创建索引库 需要注意的是.setRefresh(true)这里一定要设置,否则第一次建立索引查找不到数据
IndexRequestBuilder requestBuilder = client.prepareIndex(indexname, type).setRefresh(true);
for(int i=0; i<jsondata.size(); i++){
requestBuilder.setSource(jsondata.get(i)).execute().actionGet();
}     
}
/**
* 创建索引
* @param client
* @param jsondata
* @return
*/
public IndexResponse createIndexResponse(String indexname, String type,String jsondata){
IndexResponse response = client.prepareIndex(indexname, type)
.setSource(jsondata)
.execute()
.actionGet();
return response;
}
/**
* 执行搜索
* @param queryBuilder
* @param indexname
* @param type
* @return
*/
public List<Medicine>  searcher(QueryBuilder queryBuilder, String indexname, String type){
List<Medicine> list = new ArrayList<Medicine>();
SearchResponse searchResponse = client.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 Medicine(id, name, function));
}
}
return list;
}

public static void main(String[] args) {
ElasticSearchHandler esHandler = new ElasticSearchHandler();
List<String> jsondata = DataFactory.getInitJsonData();
String indexname = "indexdemo";
String type = "typedemo";
esHandler.createIndexResponse(indexname, type, jsondata);
//查询条件
//        QueryBuilder queryBuilder = QueryBuilders.inQuery("name", "感冒");
QueryBuilder queryBuilder = QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery("id", 1));
List<Medicine> result = esHandler.searcher(queryBuilder, indexname, type);
for(int i=0; i<result.size(); i++){
Medicine medicine = result.get(i);
System.out.println("(" + medicine.getId() + ")药品名称:" +medicine.getName() + "\t\t" + medicine.getFunction());
}
}
}



package com.es;
import java.util.ArrayList;
import java.util.List;
/**
*
*
*  @version : 1.0
*  
*  @author  : 苏若年              <a href="mailto:DennisIT@163.com">发送邮件</a>
*   
*  @since   : 1.0        创建时间:    2013-4-8    上午11:38:15
*     
*  @function: TODO        
*
*/
public class DataFactory {
public static DataFactory dataFactory = new DataFactory();
private DataFactory(){
}
public DataFactory getInstance(){
return dataFactory;
}
public static List<String> getInitJsonData(){
List<String> list = new ArrayList<String>();
String data1  = JsonUtil.obj2JsonData(new Medicine(1,"银花 感冒 颗粒","功能主治:银花感冒颗粒 ,头痛,清热,解表,利咽。"));
String data2  = JsonUtil.obj2JsonData(new Medicine(2,"感冒  止咳糖浆","功能主治:感冒止咳糖浆,解表清热,止咳化痰。"));
String data3  = JsonUtil.obj2JsonData(new Medicine(3,"感冒灵颗粒","功能主治:解热镇痛。头痛 ,清热。"));
String data4  = JsonUtil.obj2JsonData(new Medicine(4,"感冒  灵胶囊","功能主治:银花感冒颗粒 ,头痛,清热,解表,利咽。"));
String data5  = JsonUtil.obj2JsonData(new Medicine(5,"仁和 感冒 颗粒","功能主治:疏风清热,宣肺止咳,解表清热,止咳化痰。"));
list.add(data1);
list.add(data2);
list.add(data3);
list.add(data4);
list.add(data5);
return list;
}
}


package com.es;
import java.io.IOException;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
/**
*
*
*  @version : 1.0
*  
*  @author  : 苏若年              <a href="mailto:DennisIT@163.com">发送邮件</a>
*   
*  @since   : 1.0        创建时间:    2013-4-8    上午11:34:56
*     
*  @function: TODO        
*
*/
public class JsonUtil {
/**
* 实现将实体对象转换成json对象
* @param medicine    Medicine对象
* @return
*/
public static String obj2JsonData(Medicine medicine){
String jsonData = null;
try {
//使用XContentBuilder创建json数据
XContentBuilder jsonBuild = XContentFactory.jsonBuilder();
jsonBuild.startObject()
.field("id",medicine.getId())
.field("name", medicine.getName())
.field("funciton",medicine.getFunction())
.endObject();
jsonData = jsonBuild.string();
System.out.println(jsonData);
} catch (IOException e) {
e.printStackTrace();
}
return jsonData;
}
}


package com.es;
/**
*
*
*  @version : 1.0
*  
*  @author  : 苏若年              <a href="mailto:DennisIT@163.com">发送邮件</a>
*   
*  @since   : 1.0        创建时间:    2013-4-8    下午04:51:03
*     
*  @function: TODO        
*
*/
public class Medicine {
private Integer id;
private String name;
private String function;
public Medicine() {
super();
}
public Medicine(Integer id, String name, String function) {
super();
this.id = id;
this.name = name;
this.function = function;
}
//getter and  setter ()
public String getFunction() {
return function;
}
public void setFunction(String function) {
this.function = function;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-379293-1-1.html 上篇帖子: elasticsearch中文分词集成 下篇帖子: Elasticsearch基础教程
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表