lucene學習的小結

pom.xml設置

    <dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>org.apache.lucene</groupId><artifactId>lucene-core</artifactId><version>5.3.1</version></dependency><dependency><groupId>org.apache.lucene</groupId><artifactId>lucene-queryparser</artifactId><version>5.3.1</version></dependency><dependency><groupId>org.apache.lucene</groupId><artifactId>lucene-analyzers-common</artifactId><version>5.3.1</version></dependency><dependency><groupId>org.apache.lucene</groupId><artifactId>lucene-analyzers-smartcn</artifactId><version>5.3.1</version></dependency><dependency><groupId>org.apache.lucene</groupId><artifactId>lucene-highlighter</artifactId><version>5.3.1</version></dependency>

?

生成索引IndexingTest.java

package com.chabansheng.lucene;import java.nio.file.Paths;import ...;public class IndexingTest {private String ids[]={"1","2","3","4"};private String authors[]={"Jack","Marry","John","Json"};private String positions[]={"accounting","technician","salesperson","boss"};private String titles[]={"Java is a good language.","Java is a cross platform language","Java powerful","You should learn java"};private String contents[]={"If possible, use the same JRE major version at both index and search time.","When upgrading to a different JRE major version, consider re-indexing. ","Different JRE major versions may implement different versions of Unicode,","For example: with Java 1.4, `LetterTokenizer` will split around the character U+02C6,"};private Directory dir;/*** 生成索引* @throws Exception*/@Testpublic void index()throws Exception{dir=FSDirectory.open(Paths.get("D:\\lucene3"));//獲取IndexWriter實例Analyzer analyzer=new StandardAnalyzer(); // 標準分詞器IndexWriterConfig iwc=new IndexWriterConfig(analyzer);IndexWriter writer=new IndexWriter(dir, iwc);for(int i=0;i<ids.length;i++){Document doc=new Document();doc.add(new StringField("id", ids[i], Field.Store.YES));doc.add(new StringField("author",authors[i],Field.Store.YES));doc.add(new StringField("position",positions[i],Field.Store.YES));// 加權操作TextField field=new TextField("title", titles[i], Field.Store.YES);if("boss".equals(positions[i])){field.setBoost(1.5f);}doc.add(field);doc.add(new TextField("content", contents[i], Field.Store.NO));writer.addDocument(doc); // 添加文檔
        }writer.close();}/*** 查詢索引方式一* @throws Exception*/@Testpublic void search()throws Exception{dir=FSDirectory.open(Paths.get("D:\\lucene"));IndexReader reader=DirectoryReader.open(dir);IndexSearcher is=new IndexSearcher(reader);String searchField="title";String q="java";//Term方式查詢Term t=new Term(searchField,q);Query query=new TermQuery(t);TopDocs hits=is.search(query, 10);System.out.println("匹配 '"+q+"',總共查詢到"+hits.totalHits+"個文檔");for(ScoreDoc scoreDoc:hits.scoreDocs){Document doc=is.doc(scoreDoc.doc);System.out.println(doc.get("author"));}reader.close();}}

查詢索引方式二Searcher.java

package com.chabansheng.lucene;import java.io.StringReader;
import java.nio.file.Paths;import ...;public class Searcher {public static void search(String indexDir,String q)throws Exception{Directory dir=FSDirectory.open(Paths.get(indexDir));IndexReader reader=DirectoryReader.open(dir);IndexSearcher is=new IndexSearcher(reader);//QueryParser查詢方式// Analyzer analyzer=new StandardAnalyzer(); // 標準分詞器SmartChineseAnalyzer analyzer=new SmartChineseAnalyzer();QueryParser parser=new QueryParser("desc", analyzer);Query query=parser.parse(q);TopDocs hits=is.search(query, 10); //高亮行號QueryScorer scorer=new QueryScorer(query);Fragmenter fragmenter=new SimpleSpanFragmenter(scorer);SimpleHTMLFormatter simpleHTMLFormatter=new SimpleHTMLFormatter("<b><font color='red'>","</font></b>");Highlighter highlighter=new Highlighter(simpleHTMLFormatter, scorer);highlighter.setTextFragmenter(fragmenter);for(ScoreDoc scoreDoc:hits.scoreDocs){Document doc=is.doc(scoreDoc.doc);System.out.println(doc.get("city"));System.out.println(doc.get("desc"));String desc=doc.get("desc");if(desc!=null){TokenStream tokenStream=analyzer.tokenStream("desc", new StringReader(desc));System.out.println(highlighter.getBestFragment(tokenStream, desc));}}reader.close();}public static void main(String[] args) {String indexDir="D:\\lucene2";String q="南京文明";try {search(indexDir,q);} catch (Exception e) {// TODO Auto-generated catch block
            e.printStackTrace();}}
}

?

package com.chabansheng.lucene;
import java.nio.file.Paths;
import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.standard.StandardAnalyzer;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.document.StringField;import org.apache.lucene.document.TextField;import org.apache.lucene.index.DirectoryReader;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.index.Term;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.Query;import org.apache.lucene.search.ScoreDoc;import org.apache.lucene.search.TermQuery;import org.apache.lucene.search.TopDocs;import org.apache.lucene.store.Directory;import org.apache.lucene.store.FSDirectory;import org.junit.Test;
public class IndexingTest {
private String ids[]={"1","2","3","4"};private String authors[]={"Jack","Marry","John","Json"};private String positions[]={"accounting","technician","salesperson","boss"};private String titles[]={"Java is a good language.","Java is a cross platform language","Java powerful","You should learn java"};private String contents[]={"If possible, use the same JRE major version at both index and search time.","When upgrading to a different JRE major version, consider re-indexing. ","Different JRE major versions may implement different versions of Unicode,","For example: with Java 1.4, `LetterTokenizer` will split around the character U+02C6,"};private Directory dir;/** * 生成索引 * @throws Exception */@Testpublic void index()throws Exception{dir=FSDirectory.open(Paths.get("D:\\lucene3"));//獲取IndexWriter實例Analyzer analyzer=new StandardAnalyzer(); // 標準分詞器IndexWriterConfig iwc=new IndexWriterConfig(analyzer);IndexWriter writer=new IndexWriter(dir, iwc);for(int i=0;i<ids.length;i++){Document doc=new Document();doc.add(new StringField("id", ids[i], Field.Store.YES));doc.add(new StringField("author",authors[i],Field.Store.YES));doc.add(new StringField("position",positions[i],Field.Store.YES));// 加權操作TextField field=new TextField("title", titles[i], Field.Store.YES);if("boss".equals(positions[i])){field.setBoost(1.5f);}doc.add(field);doc.add(new TextField("content", contents[i], Field.Store.NO));writer.addDocument(doc); // 添加文檔}writer.close();}
/** * 查詢 * @throws Exception */@Testpublic void search()throws Exception{dir=FSDirectory.open(Paths.get("D:\\lucene3"));IndexReader reader=DirectoryReader.open(dir);IndexSearcher is=new IndexSearcher(reader);String searchField="title";String q="java";//Term方式查詢Term t=new Term(searchField,q);Query query=new TermQuery(t);TopDocs hits=is.search(query, 10);System.out.println("匹配 '"+q+"',總共查詢到"+hits.totalHits+"個文檔");for(ScoreDoc scoreDoc:hits.scoreDocs){Document doc=is.doc(scoreDoc.doc);System.out.println(doc.get("author"));}reader.close();}}

?

轉載于:https://www.cnblogs.com/375163374lsb/p/10542985.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/449587.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/449587.shtml
英文地址,請注明出處:http://en.pswp.cn/news/449587.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

并行計算的專訪

摘要&#xff1a;社區之星第9期采訪的嘉賓是香港浸會大學計算機在讀博士、浪潮高性能計算顧問趙開勇。此次他為我們揭開了高性能計算的神秘面紗&#xff0c;為讀者講解自己的經驗心得。并且他認為基于移動設備的高性能計算將會成為未來潮流&#xff0c;低功耗、高性能也將成為一…

CentOS6.5 搭建 LNMP (linux + nginx + mysql + php)

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 1&#xff1a;查看環境&#xff1a; 12[root10-4-14-168 html]# cat /etc/redhat-releaseCentOS release 6.5 (Final)2&#xff1a;關掉…

正睿2019省選附加賽 Day10 (這篇其實已經都咕咕了...)

目錄 2019.3.13A.算算算(二項式定理 斯特林數)B.買買買C.樹樹樹2019.3.13比賽鏈接 A.算算算(二項式定理 斯特林數) 題目鏈接 \(x^k\)可以用二項式定理展開&#xff0c;需要維護的就是\(0\sim k\)次方的\(\sum_{j}F(j,i)\)。加入一個數時&#xff0c;每一項都要再用一遍二項式定…

freemarker 從 spring boot execute jar可執行jar中訪問模板文件

2019獨角獸企業重金招聘Python工程師標準>>> private static Configuration freemarkerCfg null;static {freemarkerCfg new Configuration();//freemarker的模板目錄try {String pathPrefix "/";// 為了支持能從execute jar 中獲取模板文件URI uri C…

獲取所有股票數據

#%%#先引入后面可能用到的包&#xff08;package&#xff09; import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set() %matplotlib inline #正常顯示畫圖時出現的中文和負號 from pylab import mpl mpl.rcParams[font.…

POWERSPLOIT-Recon(信息偵察)腳本滲透實戰

Recon(信息偵察)模塊 a) 調用invoke-Portscan掃描內網主機的端口。 1&#xff09;通過IEX下載并調用invoke-portscan。 PS C:\Users\Administrator> IEX(New-Object net.webclient).DownloadString("http://192.168.190.141/PowerSploit/Recon/Invoke -Portscan.ps1&qu…

股票代碼前面為0,補齊6位數

df[code] df[code].apply(lambda x:str(x).zfill(6))

在CentOS 6上搭建LNMP環境

簡介LNMP是Linux、Nginx、MySQL和PHP的縮寫&#xff0c;這個組合是最常見的WEB服務器的運行環境之一。本文將帶領大家在CentOS 6操作系統上搭建一套LNMP環境。 本教程適用于CentOS 6.x版本。 在安裝LNMP環境之前&#xff0c;您需要先對CentOS操作系統做一些初始化的工作&#x…

前端技術周刊 2019-01-21:跨端開發的三條路線

2019-01-21 前端快爆 微軟 Edge 開發者意圖為 Chrome 實現 HTML Modules&#xff0c;該規范用來替代之前的 HTML Imports。其優點是基于 ES Modules&#xff0c;可以避免全局對象污染、腳本解析阻塞等問題。?點評&#xff1a;舉報&#xff0c;有人在「秀恩愛」&#xff01; &l…

分配內存的方法,需要32位對齊

type 是char&#xff0c;short&#xff0c;int 。 #define DATA_ALIGN 1 #if DATA_ALIGN && WIN32 && (_MSC_VER > 1300) #define my_malloc(type,len) _aligned_malloc(sizeof(type) *(len), 32) #define my_free(ptr) _aligned_free(ptr) #e…

zabbix-02-CentOS7.4安裝zabbix4.0

一、環境準備 1.1 主機規劃 這里先對本次實驗的機器做一個規劃&#xff0c;之后的實驗均通過這兩臺機器完成。 序號IP地址主機名CPU內存硬盤安裝服務110.0.0.11zabbix-server1C2G20GBzabbix服務端210.0.0.12zabbix-agent1C1G20GBzabbix客戶端1.2 操作系統選擇 操作系統選擇&…

再談并發

再談并發 上一篇python并發中講到了&#xff0c;使用多進程&#xff0c;多線程&#xff0c;多任務來加快程序的運行。其中講到的一點似乎有點問題&#xff0c;操作系統中線程是調度器的最小執行單位&#xff0c;那為何python中的多線程無法利用多核&#xff0c;只能在一個處理器…

centos6.8安裝docker,kong-dashboard并實現頁面訪問

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 我們通過kong-dashboard的admin-UI管理界面進行直觀的查看。最終顯示界面如圖&#xff1a; 因為這個kong-dashboard要用到docker&#x…

leetcood學習筆記-204-計算質數

題目描述&#xff1a; 第一次提交;(超時)&#xff1a; class Solution:def countPrimes(self, n: int) -> int:count 0for i in range(2,n):for j in range(2,i1):if i%j 0 and j!i:breakif ji:count1return count 別人家的&#xff1a; 這題搜到一個非常牛逼的算法,叫做厄…

linux man

nameman - 即 manual &#xff0c;在線查看命令手冊。 描述man 是一個系統手冊&#xff0c;man 的每一個選項通常是命令名&#xff0c;查找顯示選項中的每個相關聯的手冊頁&#xff0c;默認操作按照指順序&#xff0c;按屏打印顯示。 下表顯示手冊章節號&#xff0c;以及它們包…

centos-install-kong-cassandra

轉自&#xff1a;http://blog.54im.com/2016/12/15/centos-install-kong-cassandra/#前置閱讀 對于一些傳統的大型項目&#xff0c;傳統的方式會有一些缺陷&#xff0c;比如說新人熟悉系統成本高&#xff08;因為整個系統作為一個整體&#xff0c;彼此會有一定的牽連&#xff0…

akshare做mfi策略

#!/usr/bin/env python # coding: utf-8#先引入后面可能用到的包&#xff08;package&#xff09; import pandas as pd import numpy as np import matplotlib.pyplot as plt#正常顯示畫圖時出現的中文和負號 from pylab import mpl mpl.rcParams[font.sans-serif][SimHei] …

第二章學習小結

第二章學習小結 對比于上學期所學的知識&#xff0c;能切實感覺到這個學期的課程更加深入和抽象&#xff0c;在學習上難度也有所增加&#xff0c;雖然上個學期就聽老師推薦過博客園&#xff0c;但是真正開始寫博客還是第一次&#xff0c;最直觀的感受就是在完成博客的過程中&am…

翁同龢后人向上海博物館捐贈兩件重要家藏

1月24日&#xff0c;翁萬戈先生捐贈書畫儀式在上海博物館內舉行。 上海博物館 供圖 1月24日&#xff0c;翁萬戈先生捐贈書畫儀式在上海博物館內舉行。 上海博物館 供圖 中新網上海1月24日電 (王笈)翁同龢后人翁以鈞24日攜夫人柳至善&#xff0c;代表翁萬戈將兩件翁氏家族的重要…