Solr客户端


参考文献地址:http://www.solr.cc/blog/?p=1296

 

Solr版本:4.7.0

 

一、依赖的jar

Solr客户端_第1张图片

Maven配置

<dependency>
    	<groupId>org.apache.solr</groupId>
    	<artifactId>solr-solrj</artifactId>
    	<version>4.7.0</version>
    	<scope>test</scope>
</dependency>

二、添加索引

SolrjPopulator.java

package com.clj.test.solr.solr4;

import java.io.IOException;

import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.SolrInputDocument;

/**
 * solr 4.X
 * 添加索引
 * 
 * @author  Administrator
 * @version  [版本号, 2014年3月9日]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class SolrjPopulator
{
    public static void main(String[] args) throws IOException, SolrServerException {
        HttpSolrServer server = new HttpSolrServer("http://localhost:8080/solr");
        for (int i = 0; i < 1000; ++i) {
            SolrInputDocument doc = new SolrInputDocument();
            doc.addField("cat", "book");
            doc.addField("id", "book-" + i);
            doc.addField("name", "The Legend of Po part " + i);
            server.add(doc);
            if (i % 100 == 0)
                server.commit(); // periodically flush
        }
        server.commit();
    }
}

三、搜索

SolrJSearcher.java

package com.clj.test.solr.solr4;

import java.net.MalformedURLException;

import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.ModifiableSolrParams;

/**
 * solr 4.X
 * 查询数据
 * 
 * @author  Administrator
 * @version  [版本号, 2014年3月9日]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class SolrJSearcher
{
    public static void main(String[] args) throws MalformedURLException, SolrServerException {
        HttpSolrServer solr = new HttpSolrServer("http://localhost:8080/solr");
 
        ModifiableSolrParams params = new ModifiableSolrParams();
        params.set("q", "cat:book");
        params.set("defType", "edismax");
        params.set("start", "0");
 
        QueryResponse response = solr.query(params);
        SolrDocumentList results = response.getResults();
        for (int i = 0; i < results.size(); ++i) {
            System.out.println(results.get(i));
        }
    }
}

搜索结果:

Solr客户端_第2张图片


你可能感兴趣的:(搜索,Solr)