Skip to content

Instantly share code, notes, and snippets.

@myokoym
Created June 25, 2015 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myokoym/a301de902e30ad561cbd to your computer and use it in GitHub Desktop.
Save myokoym/a301de902e30ad561cbd to your computer and use it in GitHub Desktop.
[WIP] A on-memory full-text search engine by pure Ruby.
#!/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