倒排索引的簡單實現,排索引簡單實現

來源:互聯網
上載者:User

倒排索引的簡單實現,排索引簡單實現
倒排索引的簡單實現
   倒排索引是搜尋引擎中常用的演算法,主要用來實現full text searching,建立關鍵詞和所在文檔的映射關係,很多強大的功能都建立在此基礎之上,關於Inverted Index的詳盡描述可以看Wikipedia。下面按照自己的想法實現之,只是為了體會這個資料結構的運作。  todo:如果要搜完整的出現一句話如“what is it”可以分別搜這幾個單詞然後看出現在同一個檔案連續位置的結果即可,集合運算。
package mythought.invertedindex;import java.io.BufferedReader;import java.io.FileReader;import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Set;public class InvertedIndex {    // key word <----> doc file    private Map<String, Set<String>> indexs = new HashMap<String, Set<String>>();    // 這裡假設都是小檔案    public void addFile(String fileName, String content) {        String[] words = content.split(" ");        for (int i = 0; i < words.length; i++) {            String word = words[i];            // only record first appeared position            Set<String> wordIndex = indexs.get(word);            if (wordIndex == null) {                wordIndex = new HashSet<String>();                indexs.put(word, wordIndex);            }            wordIndex.add("("+fileName + "," + i+")");        }    }        public void addFile(String fileName) throws Exception{        BufferedReader br = new BufferedReader(new FileReader(fileName));        try {            StringBuilder sb = new StringBuilder();            String line = br.readLine();            while (line != null) {                sb.append(line);                sb.append(" ");// 每行直接串接                line = br.readLine();            }            this.addFile(fileName, sb.toString());        } catch(Exception e){            e.printStackTrace();        }finally {            br.close();        }    }    public Set<String> search(String keyword) {        Set<String> results = indexs.get(keyword);        return new HashSet<String>(results);    }    public static void main(String[] args) throws Exception{        InvertedIndex test = new InvertedIndex();        test.addFile("file1", "hello fuck world todotodo");        test.addFile("file2", "go to get it if you want it");        test.addFile("C:/data/hello.txt");        System.out.println(test.search("it"));        System.out.println(test.search("you"));        System.out.println(test.search("vonzhou"));    }}
運行結果:[(file2,7), (file2,3)][(file2,5)][(C:/data/hello.txt,4)] 
參考:1.http://en.wikipedia.org/wiki/Inverted_index
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.