1. 程式人生 > >java 使用elasticsearch 以及複雜查詢語句構建

java 使用elasticsearch 以及複雜查詢語句構建

elastcisearch 為java開發了API介面,方便java程式的使用。
首先引入jar包,需要跟elasticsearch版本對應。下面是maven的引入,也可以下載jar包引入。

    <!-- http://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId
>
<version>1.6.0</version> </dependency>

使用這種 方式,可只使用一個client端,不會重複申請客戶端

    public static final String CLUSTERNAME ="elasticsearch"; //叢集模型
    public static final String INDEX = "base_kb"; //索引名稱
    public static final String TYPE = "entity";//型別名稱
    public static final
String HOST = "10.110.6.43"; //伺服器地址 public static final int PORT = 9300; //服務埠 TCP為9300 IP為9200 static Map<String, String> map = new HashMap<String, String>(); static Settings settings = ImmutableSettings.settingsBuilder().put(map).put("cluster.name",CLUSTERNAME) .put("client.transport.sniff"
, true).build(); private static TransportClient client; static { try { Class<?> clazz = Class.forName(TransportClient.class.getName()); Constructor<?> constructor = clazz.getDeclaredConstructor(Settings.class); constructor.setAccessible(true); client = (TransportClient) constructor.newInstance(settings); client.addTransportAddress(new InetSocketTransportAddress(HOST, PORT)); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static synchronized TransportClient geTransportClient(){ return client; }

在java中構造複雜json資料是讓人非常頭疼的一件事,在使用java呼叫API時,語句其實是已經構造了,因此只需使用模板就可以了,模板的使用請看另一篇博文。

        public static  SearchHits getHits(String mention,String mention_type, String lang){
        Map<String, Object> templateParams = new HashMap<String, Object>();
        templateParams.put("mention_"+mention_type, mention);

        TransportClient client = geTransportClient();
        SearchResponse actionGet = client.prepareSearch("base_kb")
                                        .setTypes("entity")                                     
                                        .setTemplateName("template_" + mention_type + "_" + lang)
                                        .setTemplateType(ScriptService.ScriptType.FILE)
                                        .setTemplateParams(templateParams)                      
//                                      .setQuery( QueryBuilders.termQuery("_id", "2"))
                                        .execute()
                                        .actionGet();
        return actionGet.getHits();     
    }


        public static void main(String[] args) {
        // TODO Auto-generated method stub  
//      
        String mention = "中國";
        String mention_type = "ORG";
        String lang = "cmn";

        SearchHits hits = getHits(mention, mention_type, lang);
//      System.out.println(hits.totalHits());
        for (SearchHit hit : hits.getHits()){ //getHits 的使用         
            System.out.println(hit.getId());
            System.out.println(hit.getFields().get("rs_label_zh").getValue());//這樣可以獲得屬性的值
            System.out.println(hit.getFields().get("f_common.topic.description_zh").getValue());
        }