您的位置:首页 > 编程语言 > Java开发

使用Java调用ElasticSearch提供的相关API进行数据搜索完整实例演示

2015-02-10 17:32 1106 查看
安装包下载

当前最新版本为 :0.20.6

http://www.elasticsearch.org/download/

官方视频教程

http://www.elasticsearch.org/videos/
官方网站
http://www.elasticsearch.org/
Window 环境

下载完解开有以下个包 :

bin 是运行的脚本, config 是设置文件, lib 是放依赖的包。




启动解压目录下的 bin 名称的文件夹,双击 elasticsearch.bat 文件,就可以启动 elasticsearch ,启动成功界面如下 :


启动成功后 , 会在解压目录下增加 2 个文件件 ,data 用于数据存储 , logs 用于日志记录 , 可以自己创建 plugins 目录中用于放置自己的插件。

此时可以在浏览器中输入 : http://localhost:9200/

"ok" : true, 
"status" : 200, 
"name" : "Glob Herman", 
"version" : { "number" : "0.20.6", "snapshot_build" : false }, "tagline" : "You Know, for Search" }


出现上面结果 , 表示成功启动!



集成分词器的 ElasticSearch 下载地址 :

https://github.com/medcl/elasticsearch-rtf



Java 模拟简单搜索

实体类

package org.dennisit.entity;
/**
 * 
 *
 *  @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 ()
}


模拟数据

package org.dennisit.entity;
import java.util.ArrayList;
import java.util.List;
import org.dennisit.util.JsonUtil;

/**
 * 
 *
 *  @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 org.dennisit.util;
import java.io.IOException;
import org.dennisit.entity.Medicine;
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;
    }

}


ElasticSearch 核心搜索模拟类

package org.dennisit.elastic.process;

import java.util.ArrayList;
import java.util.List;
import org.dennisit.entity.DataFactory;
import org.dennisit.entity.Medicine;
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.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("127.0.0.1");
    }
    
    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(ipAddress, 9300));
    }
    
    
    /**
     * 建立索引,索引建立好之后,会在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.hits();
        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.fieldQuery("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());
        }
    }
}


启动 ElasticSearch(window 下 bin/elasticsearch.bat)




程序运行前, 默认的 nodes 目录下没有内容 , 运行程序后会建立如下目录



控制台输出信息

{"id":1,"name":"银花 感冒 颗粒","funciton":"功能主治:银花感冒颗粒 ,头痛,清热,解表,利咽。"}
{"id":2,"name":"感冒  止咳糖浆","funciton":"功能主治:感冒止咳糖浆,解表清热,止咳化痰。"}
{"id":3,"name":"感冒灵颗粒","funciton":"功能主治:解热镇痛。头痛 ,清热。"}
{"id":4,"name":"感冒  灵胶囊","funciton":"功能主治:银花感冒颗粒 ,头痛,清热,解表,利咽。"}
{"id":5,"name":"仁和 感冒 颗粒","funciton":"功能主治:疏风清热,宣肺止咳,解表清热,止咳化痰。"}
查询到记录数=5
(4)药品名称:感冒  灵胶囊        功能主治:银花感冒颗粒 ,头痛,清热,解表,利咽。
(1)药品名称:银花 感冒 颗粒        功能主治:银花感冒颗粒 ,头痛,清热,解表,利咽。
(2)药品名称:感冒  止咳糖浆        功能主治:感冒止咳糖浆,解表清热,止咳化痰。
(3)药品名称:感冒灵颗粒        功能主治:解热镇痛。头痛 ,清热。
(5)药品名称:仁和 感冒 颗粒        功能主治:疏风清热,宣肺止咳,解表清热,止咳化痰。


集群管理工具Head 查看信息

附录 :

ElasticSearch 安装插件 elasticsearch-head 插件




安装完之后 , 在 lasticsearch-0.20.6\plugins\ 目录下就多了 head 插件

直接打开目录中的 index.html 文件即可进入管理工具
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐