lucene实现全局搜索

本文详细介绍了如何使用Lucene 5.3.1进行文本索引的创建和查询过程。通过Spring框架整合Lucene,演示了从数据库读取数据创建索引,并实现基于关键词的全文搜索。此外,还展示了如何使用Highlighter进行搜索结果的高亮显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.导lucene依赖我使用的是5.3.1的
2.创建索引

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value={"classpath:springMVC.xml"})
public class LuceneTest{
	@Autowired
	private StreetMapper streetMapper;
	//创建索引
	@Test
	public void test() throws Exception{
		Analyzer analyzer = new StandardAnalyzer();
		Directory directory = FSDirectory.open(Paths.get("D:\\index"));//创建索引文件夹
		List<Street> queryStreetName = streetMapper.queryStreetName();
		IndexWriterConfig config = new IndexWriterConfig(analyzer);
		IndexWriter iwriter = new IndexWriter(directory, config);
		for(Street street:queryStreetName){
			Document doc = new Document();
			System.out.print(street.getsName());
			doc.add(new TextField("sName", street.getsName(), Store.YES));
			//doc.add(new TextField("path", fi.getAbsolutePath(), Store.YES));
			iwriter.addDocument(doc);
		}
		iwriter.close();
	}
	}

3.开始查询

//查询
	@Test
	public void queryTest() throws Exception{
		Directory directory = FSDirectory.open(Paths.get("D:\\index"));
	    String text = "东晓";
	    DirectoryReader ireader = DirectoryReader.open(directory);
	    IndexSearcher isearcher = new IndexSearcher(ireader);
	    Analyzer analyzer = new StandardAnalyzer();
	    Query query =   null ;  
	    QueryParser qp =   new  QueryParser("sName", analyzer);   
        query =  qp.parse(text);
	    /*Term term = new Term("sName", text.toLowerCase());
	    TermQuery termQuery = new TermQuery(term);*/
        QueryScorer scorer = new QueryScorer(query);
        SimpleHTMLFormatter simpleHtmlFormatter = new SimpleHTMLFormatter("<B>","</B>");//设定高亮显示的格式<B>keyword</B>,此为默认的格式  
        Highlighter highlighter = new Highlighter(simpleHtmlFormatter,scorer);   
        highlighter.setTextFragmenter(new SimpleFragmenter(20));//设置每次返回的字符数
        ScoreDoc[] hits = isearcher.search(query,10000).scoreDocs;
	    for (int i = 0; i < hits.length; i++) {
	      Document hitDoc = isearcher.doc(hits[i].doc);
	      System.out.print(hitDoc.get("sName")+"\n");
          String str = highlighter.getBestFragment(analyzer, "东晓", hitDoc.get("sName")) ;
          System.out.println(str);   
	    }
	    ireader.close();
	    directory.close();
	}

4.springmvc.xml

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    	<!-- 运行用 -->
        <!-- <property name="driverClassName">
            <value>org.logicalcobwebs.proxool.ProxoolDriver</value>
        </property>
        <property name="url">
            <value>proxool.dbname2</value>
        </property> -->
        <!-- 测试用 -->
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
        <property name="url" value="jdbc:oracle:thin:@xxx:1521:orcl"></property>
        <property name="username" value="xxx"></property>
        <property name="password" value="xxx"></property>
    </bean>

本人亲测能用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值