使用solrj api操作solr

1.创建maven项目。并添加相关的依赖。

  <dependencies>
        <dependency>
            <groupId>org.apache.solr</groupId>
            <artifactId>solr-solrj</artifactId>
            <version>5.3.1</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.7</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.3</version>
        </dependency>
    </dependencies>

2.新建log4j.properties。

log4j.rootLogger=DEBUG,A1
log4j.logger.com.taotao = DEBUG
log4j.logger.org.mybatis = DEBUG

log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n

3.创建与 schema.xml文件相对应的javabean,这里命名为Notice。并添加@Field注解,生成getter和setter方法。

public class Notice {
  @Field("id")
  private String id;
  @Field
  private String title;
  @Field
  private String subject;
  @Field
  private String description;
}

4.创建测试类SolrjTest,初始化HttpSolrClient。

public class SolrjTest {
  private HttpSolrClient httpSolrClient;
  @Before
  public void setUp() throws Exception {
    // 在url中指定core名称:notice
    String url = "http://localhost:777/solr/notice/";
    HttpSolrClient httpSolrClient = new HttpSolrClient(url);
    httpSolrClient.setParser(new XMLResponseParser()); // 设置响应解析器
    httpSolrClient.setConnectionTimeout(500); // 建立连接的最长时间
    this.httpSolrClient = httpSolrClient;
  }
}

5.测试添加。

@Test
  public void testAdd() throws IOException, SolrServerException {
    Notice notice = new Notice();
    String desc = "该应用场景为AdMaster DMP缓存存储需求,DMP需要管理非常多的第三方id数据,其中包括各媒体cookie与自身cookie(以下统称admckid)的mapping关系,还包括了admckid的人口标签、移动端id(主要是idfa和imei)的人口标签,以及一些黑名单id、ip等数据。";
    notice.setId(UUID.randomUUID().toString());
    notice.setTitle("Redis百亿级Key存储方案");
    notice.setSubject("该应用场景为AdMaster DMP缓存存储需求");
    notice.setDescription(desc);
    this.httpSolrClient.addBean(notice);
    this.httpSolrClient.commit();
  }

6.测试查询。

@Test
  public void testQuery() throws SolrServerException, IOException{
    String keywords = "应用";
    int page = 1;
    int rows = 10;
    
    SolrQuery solrQuery = new SolrQuery(); // 构造搜索条件
    solrQuery.setQuery("text:" + keywords); // 搜索关键词
    // 设置分页 
    solrQuery.setStart((Math.max(page, 1) - 1) * rows);
    solrQuery.setRows(rows);
    
    QueryResponse queryResponse = this.httpSolrClient.query(solrQuery);
    List<Notice> notices = queryResponse.getBeans(Notice.class);
    for (Notice notice : notices) {
      System.out.println(notice.toString());
    }
  }

7.高亮。

@Test
  public void testHighlighting() throws SolrServerException, IOException{
    String keywords = "应用";
    int page = 1;
    int rows = 10;
    
    SolrQuery solrQuery = new SolrQuery(); // 构造搜索条件
    solrQuery.setQuery("text:" + keywords); // 搜索关键词
    // 设置分页 
    solrQuery.setStart((Math.max(page, 1) - 1) * rows);
    solrQuery.setRows(rows);
    
    // 是否需要高亮
    boolean isHighlighting = !StringUtils.equals("*", keywords) && StringUtils.isNotEmpty(keywords);
    if (isHighlighting) {
      // 设置高亮
      solrQuery.setHighlight(true); // 开启高亮组件
      solrQuery.addHighlightField("title");// 高亮字段
      solrQuery.addHighlightField("subject");
      solrQuery.setHighlightSimplePre("<span style='color:red;'>");// 标记,高亮关键字前缀
      solrQuery.setHighlightSimplePost("</span>");// 后缀
    }
    
    QueryResponse queryResponse = this.httpSolrClient.query(solrQuery);
    List<Notice> notices = queryResponse.getBeans(Notice.class);
    
    if (isHighlighting) {
      // 将高亮的标题数据写回到数据对象中
      Map<String, Map<String, List<String>>> map = queryResponse.getHighlighting();
      for (Map.Entry<String, Map<String, List<String>>> highlighting : map.entrySet()) {
        for (Notice notice : notices) {
          if (!highlighting.getKey().equals(notice.getId().toString())) {
            continue;
          }
          if(highlighting.getValue().get("title") != null){
            notice.setTitle(StringUtils.join(highlighting.getValue().get("title"), ""));
          }
          if(highlighting.getValue().get("subject") != null){
            notice.setSubject(StringUtils.join(highlighting.getValue().get("subject"),""));
          }
          break;
        }
      }
    }
    
    for (Notice notice : notices) {
      System.out.println(notice.toString());
    }
  }

8.删除。

@Test
  public void testDelete() throws SolrServerException, IOException{
    String id = "30a6d598-9762-455a-94f7-21fa011640d1";
    this.httpSolrClient.deleteById(id);
    this.httpSolrClient.commit();
  }

 

源码下载:http://pan.baidu.com/s/1bpBkHOF 密码:87ci

posted @ 2016-08-22 20:30  s百世经纶  阅读(9126)  评论(1编辑  收藏  举报