SolrJ增刪改查操作(入門級)

最近學習了Lucene和Solr,Java操作Solr就叫SolrJ了,這是我膚淺的理解,下面記錄下簡單的一些操作,方面日後複習

 

首先導入jar包座標

<!--SolrJ-->
        <dependency>
            <groupId>org.apache.solr</groupId>
            <artifactId>solr-solrj</artifactId>
            <version>7.7.2</version>
        </dependency>

 

然後編寫測試類代碼(隨着Jar包版本更新,寫法會不一樣,注意一下):

 

添加:

@Test
    public void testAdd() throws IOException, SolrServerException {

        String solrURL="http://localhost:8080/solr/collection1";

        HttpSolrClient.Builder builder = new HttpSolrClient.Builder(solrURL);
        HttpSolrClient client = builder.build();

        SolrInputDocument doc = new SolrInputDocument();
        doc.setField("id","123");
        doc.setField("age",22);
        
        //doc.setField("asd","nono");
        /*添加一個不存在的Field數據,竟然不報錯*/
        
        client.add(doc);
        client.commit();
        /*記得提交,不然結果不生效*/

    }

 

刪除

@Test
    public void testDelete() throws IOException, SolrServerException {

        String solrURL="http://localhost:8080/solr/collection1";

        HttpSolrClient.Builder builder = new HttpSolrClient.Builder(solrURL);
        HttpSolrClient client = builder.build();

        client.deleteById("123");

        /*刪除所有*/
        //client.deleteByQuery("*:*");
        
        client.commit();
    }

 

修改

修改與添加調用的方法是一致的,都是使用add方法,當ID已經存在時,直接覆蓋,這樣等同於修改

 

查詢(重點)

 @Test
    public void test2() throws IOException, SolrServerException {
        String solrURL="http://localhost:8080/solr/collection1";
        HttpSolrClient.Builder builder = new HttpSolrClient.Builder(solrURL);
        HttpSolrClient client = builder.build();

        SolrQuery query = new SolrQuery();
//        query.setFields("id");
        query.set("q","*:*");
        query.set("fq","age:[1 TO 20]");
        query.addSort("age", SolrQuery.ORDER.desc);

        QueryResponse response = client.query(query);
        SolrDocumentList results = response.getResults();
        long num = results.getNumFound();

        System.out.println("num "+num);
        for (SolrDocument doc : results) {
            System.out.printf("id:%s,name:%s age:%s\n", doc.get("id"), doc.get("name"), doc.get("age"));
        }

    }

 

修改:(api沒有修改的方法,只能通過id,先獲取之前的doc裏面的值,然後新建一個doc,進行覆蓋,id相同就可以覆蓋)

        SolrInputDocument document = new SolrInputDocument();   //新的文檔,直接覆蓋舊的
        SolrDocument originalDoc = solrClient.getById(id);
        Collection<String> fieldNames = originalDoc.getFieldNames();
        for (String fieldName : fieldNames) {
            Object value = originalDoc.getFieldValue(fieldName);
            document.addField(fieldName, value);
        }
        
        solrClient.add(document);
        solrClient.commit();

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章