หน้าเว็บ

วันเสาร์ที่ 17 สิงหาคม พ.ศ. 2556

elastic search simple search : java

Continued from elastic search indexing : java

        This example i will show how to use java api for search from elastic search server that i config on this topic install elastic search on ubuntu 12.04. this example is simple search using java api if you need advance you can learn more at http://www.elasticsearch.org/guide/reference/java-api/search/

Create ElasticSearch.java and have the following code.
package com.blogspot.na5cent.elasticsearch;

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;

/**
 *
 * @author redcrow
 */
public abstract class ElasticSearch {

    //point to elastic search server
    private TransportAddress transportAddress = new InetSocketTransportAddress("192.168.1.34", 9300);

    //implements by another, return client to argument
    public abstract void perform(Client client);

    public void execute() {
        Client client = null;
        try {
            client = new TransportClient().addTransportAddress(transportAddress);
            perform(client);
        } finally {
            if (client != null) {
                client.close();
            }
        }
    }
}
Search.java
package com.blogspot.na5cent.elasticsearch;

import java.util.Map;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;

/**
 *
 * @author redcrow
 */
public class Search {

    public static void main(String[] args) {
        new ElasticSearch() {
            @Override
            public void perform(Client client) {

                //search by terminology "founder" on field "message"
                QueryBuilder queryBuilder = QueryBuilders.termQuery("message", "founder");
                
                //search on index "blogspot"
                SearchResponse response = client.prepareSearch("blogspot")
                        .setQuery(queryBuilder)
                        .execute()
                        .actionGet();
                
                 //show json response
                System.out.println("response => " + response.toString());

                //list response
                for(SearchHit hit : response.getHits().hits()){
                    for(Map.Entry<String, Object> entry : hit.getSource().entrySet()){
                        System.out.println("source => {" + entry.getKey() + " : " + entry.getValue() + "}");
                    }
                }
            }
        }.execute();
    }
}
output on console



ไม่มีความคิดเห็น:

แสดงความคิดเห็น