Lucene學習

1、原理

  • 數據:結構化數據和非結構化數據linux

    • 結構化數據:指具備固定格式或有限長度的數據,如數據庫、元數據..
    • 非結構化數據(全文數據):指不定長或無固定格式的數據,如郵件,world..
  • 搜索數據算法

    • 結構化數據:數據庫(sql語句),元數據(文件名、類型、修改時間)
    • 非結構化數據(全文數據)順序掃描(linux的grep),全文檢索(分詞)(Google和百度)
      • 順序掃描:對目標文件進行全文查詢,一個文檔一個文檔,從頭到位查詢字符串。
      • 全文檢索(分詞):根據關鍵字提早創建索引,而後對索引進行搜索。
  • 分詞索引建立(Indexing)和搜索索引(Search)sql

    • 索引建立(Indexing):將添加的全部結構化和非結構化數據提取信息,建立索引的過程。
    • 搜索索引(Search):經過查詢索引,獲取目標地址,查詢目標,返回結果
  • 底層數據結構數據庫

    • 字典(左側結構): 保存了一系列的字符串。
    • 倒排序表(右側結果):含有這些字符串的目標地址。

輸入圖片說明

* **最後的結構**
    * **document Frequency**:文檔頻次,總共右多少文件包含詞
    * **Frequency**:此文件中包含了**幾回此詞**

輸入圖片說明

  • 邏輯過程
    • 索引建立(Indexing)
      • 構建一個分詞器
      • 肯定索引文件存儲的位置,lucene提供本地文件內存存儲
      • 建立IndexWriter,進行索引文件的寫入
      • 內容提取**(根據單字、二分、詞庫分詞)**、進行索引的存儲
    • 搜索索引(Search)
      • 打開存儲位置
      • 建立搜索器
      • 查詢
      • 關閉查詢器
    • 例如:查找lucene和solr字符串的文檔
      • 取出全部保護字符串 lucene 的文檔鏈表
      • 取出包含字符串 solr 的文檔鏈表
      • 經過合併鏈表,而後返回須要目標文件

輸入圖片說明

* 總體邏輯圖

輸入圖片說明

  • 中文分詞器原理(例如:我是中國人)
    • 單字分詞:一個一個字進行分詞。("我","們","是","中","國","人")
    • 二分法:按照兩個字進行切分。("咱們","們是","是中","中國","國人")
    • 詞庫分詞:按照某種算法構造詞,而後去匹配已建好的詞庫集合,若是匹配到就切分出來成爲詞語,一般詞庫分詞被認爲是最好的中文分詞算法。

3、使用

  • 基本demo(7.2)
@Test
	public void testDemo() throws IOException{
		Analyzer analyzer = new StandardAnalyzer();
		
		//存放在disk上
		final Path path = Paths.get(targetFileIndex);
		Directory directory = FSDirectory.open(path);
		
		//寫入器
		IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
		IndexWriter iw = new IndexWriter(directory,iwc);
		
		Document doc = new Document();
		String text = "This is the text to be indexed";
		doc.add(new Field("fileName",text,TextField.TYPE_STORED));
		iw.addDocument(doc);
		iw.close();
		
	}

	@Test
	public void testFind() throws IOException, ParseException {
		Analyzer analyzer = new StandardAnalyzer();
		//從disk上讀取
		final Path path = Paths.get(targetFileIndex);
		Directory directory = FSDirectory.open(path);
		DirectoryReader dr =  DirectoryReader.open(directory);
		
		//索引查詢器
		IndexSearcher isc = new IndexSearcher(dr);
		QueryParser parser = new QueryParser("filename",analyzer);
		
		Query query = parser.parse("text");
		ScoreDoc[] hits = isc.search(query, 1000).scoreDocs;;
		
		for (int i = 0; i < hits.length; i++) {
			Document hitDoc = isc.doc(hits[i].doc);
	    }
		dr.close();
	    directory.close();
	}
相關文章
相關標籤/搜索