Solr / Lucene测试查询再次docs没有索引

时间:2012-04-14 11:18:03

标签: solr lucene

我需要在实际索引它们之前测试某些文档是否与查询匹配。你会怎么做?我正在考虑的一种可能性是在内存上运行简单的lucene索引(ramdisk?)并遵循索引 - >测试查询 - >在将每个新文档发送到实际的Solr服务器之前,删除每个新文档的循环。

有人能想出更好的解决方案吗?

非常感谢。

更新

看起来这可能是一个很好的起点:http://www.lucenetutorial.com/lucene-in-5-minutes.html

1 个答案:

答案 0 :(得分:2)

由于Solr允许事务/提交,您实际上可以将它们编入索引,在执行提交之前,请先执行删除查询,删除所有不匹配的文档。

/**
 * @author Omnaest
 */
public class SolrSimpleIndexingTest
{
  protected SolrServer solrServer = newSolrServerInstance();

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

    {
      SolrInputDocument solrInputDocument = new SolrInputDocument();
      {
        solrInputDocument.addField( "id", "0" );
        solrInputDocument.addField( "text", "test1" );
      }
      this.solrServer.add( solrInputDocument );
    }
    {
      SolrInputDocument solrInputDocument = new SolrInputDocument();
      {
        solrInputDocument.addField( "id", "1" );
        solrInputDocument.addField( "text", "test2" );
      }
      this.solrServer.add( solrInputDocument );
    }
    this.solrServer.deleteByQuery( "text:([* TO *] -test2)" );
    this.solrServer.commit();

    /*
     * Now your index does only contain the document with id=1 !!
     */

    QueryResponse queryResponse = this.solrServer.query( new SolrQuery().setQuery( "*:*" ) );
    SolrDocumentList solrDocumentList = queryResponse.getResults();

    assertEquals( 1, solrDocumentList.size() );
    assertEquals( "1", solrDocumentList.get( 0 ).getFieldValue( "id" ) );
  }

  /**
   * @return
   */
  private static CommonsHttpSolrServer newSolrServerInstance()
  {
    try
    {
      return new CommonsHttpSolrServer( "http://localhost:8983/solr" );
    }
    catch ( MalformedURLException e )
    {
      e.printStackTrace();
      fail();
    }
    return null;
  }
}