Java中使用elasticsearch搜索引擎實現簡單查詢、修改等操作-已在項目中實際應用


以下的操作環境為:jdk:1.8;elasticsearch:5.2.0

maven架包下載坐標為:

<dependency>
    <groupId>org.elasticsearch.plugin</groupId>
    <artifactId>transport-netty4-client</artifactId>
    <version>5.2.0</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>5.2.0</version>
</dependency>
<dependency>
    <groupId>org.nlpcn</groupId>
    <artifactId>elasticsearch-sql</artifactId>
    <version>6.3.0.0</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.9</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>transport</artifactId>
    <version>5.2.0</version>
</dependency>

Java創建ES連接工具類:

 

//創建連接工具類
public class ESClientConnectionUtil {
    public static TransportClient client=null;
    public final static String HOST = "192.168.200.211"; //服務器部署
    public final static Integer PORT = 9301; //端口
public static TransportClient  getESClientConnection(){
    if (client == null) {
        System.setProperty("es.set.netty.runtime.available.processors", "false");
            try {
                //設置集群名稱
                Settings settings = Settings.builder().put("cluster.name", "es5").put("client.transport.sniff", true).build();
                //創建client
                client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(HOST), PORT));
            } catch (Exception ex) {
                ex.printStackTrace();
                System.out.println(ex.getMessage());
        }
    }
    return client;
}

}

 

用Java命令想elasticsearch中插入數據

 

public Map<String,Object> addTopic(KnowledgeTopicDTO knowledgeTopicDTO){
    Map<String,Object> map = new HashMap<>();
 //連接ES
    TransportClient transportClient =  ESClientConnectionUtil.getESClientConnection();
    JSONObject json = JSONObject.fromObject(knowledgeTopicDTO);//后台傳過來的對象數據轉換成json格式
    try{
        //index 索引名稱(相當於數據庫) type :類型(相當於數據庫中的表)
        IndexResponse response = transportClient.prepareIndex("knowledge", "knowledge_theme").setSource(json, XContentType.JSON).get();
        if(null !=response.getId()){
            map.put("code",200);
            return map;
        }
    }catch (Exception e){
        e.printStackTrace();
        map.put("code",500);
        return map;
    }
    return null;
}

 

使用Java根據id查詢數據

 

//連接ES
    TransportClient transportClient =  ESClientConnectionUtil.getESClientConnection();
//參數:索引名,類型(type) id
GetResponse response = client.prepareGet("knowledge", "knowledge_theme", "1")
        .setOperationThreaded(false)    // 線程安全
        .get();
JSONObject obj = new JSONObject().fromObject(response.getSourceAsString());//將json字符串轉換為json對象
InformationDTO information = (InformationDTO) JSONObject.toBean(obj, InformationDTO.class);//將json數據轉換成InformationDTO實體對象
String codes =response.getId();//獲取_id

 

根據id進行修改數據(傳入對象)

 

//knowledgeTopic為修改數據的對象
//修改狀態后的對象轉換成json數據
JSONObject fromObject= JSONObject.fromObject(knowledgeTopic);
//參數:索引名,類型(type) id(指的是_id) 要修改的json數據:fromObject
UpdateResponse updateResponse = client.prepareUpdate("knowledge", "knowledge_theme", "1")
        .setDoc(fromObject).get();

 根據id修改數據(針對單個字段修改)

   XContentBuilder source = null;
        try {
            source = XContentFactory.jsonBuilder()
                    .startObject()
                    .field("browseNum", num) //browseNum:要修改的字段名,num 修改的值
                    .endObject();
        } catch (IOException e) {
            e.printStackTrace();
        }
//client:ES連接 codes為文檔的_id UpdateResponse updateResponse = client.prepareUpdate("article", "up_information", codes).setDoc(source).get();

  

ES模糊查詢

 

SearchResponse searchResponse=null;
//連接elasticsearch
TransportClient transportClient =  ESClientConnectionUtil.getESClientConnection();
searchResponse = client.prepareSearch()
                    .setIndices("knowledge")
                    .setTypes("knowledge_theme")
                     .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                    .setScroll(TimeValue.timeValueMinutes(30)) //游標維持時間
                    .setSize(2 * 5)//實際返回的數量為10*index的主分片數
                     .setQuery(QueryBuilders.wildcardQuery("name", ("*"+name+"*").toLowerCase()))  //查詢的字段名及值
                    .execute()
                    .actionGet();

 

以上功能本人已親測過,都能實現,希望這對大家有所幫助!轉發請說明出處,本人的博客地址為:https://www.cnblogs.com/chenyuanbo/

技術在於交流!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM