Created
June 25, 2015 17:15
-
-
Save myokoym/a301de902e30ad561cbd to your computer and use it in GitHub Desktop.
[WIP] A on-memory full-text search engine by pure Ruby.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
class Database | |
attr_reader :files | |
def initialize | |
@ii = {} | |
@files = [] | |
end | |
def add(path) | |
if @files.include?(path) | |
id = @files.index(path) | |
@ii.each do |key, posting_list| | |
@ii[key].delete(id) | |
end | |
else | |
@files << path | |
id = @files.index(path) | |
end | |
File.open(path) do |file| | |
file.each_line do |line| | |
line.split(/\s/).each do |word| | |
next if word.empty? | |
@ii[word] ||= [] | |
@ii[word] << id | |
end | |
end | |
end | |
end | |
def search(query) | |
results = {} | |
ids = @ii[query] | |
ids.each do |id| | |
file = @files[id] | |
results[file] ||= 0 | |
results[file] += 1 | |
end | |
results | |
end | |
end | |
db = Database.new | |
db.add(__FILE__) | |
puts db.search("def") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment