|
| 1 | +# |
| 2 | +# Author:: Adam Jacob (<adam@opscode.com>) |
| 3 | +# Copyright:: Copyright (c) 2008 Opscode, Inc. |
| 4 | +# License:: Apache License, Version 2.0 |
| 5 | +# |
| 6 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +# you may not use this file except in compliance with the License. |
| 8 | +# You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, software |
| 13 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +# See the License for the specific language governing permissions and |
| 16 | +# limitations under the License. |
| 17 | +# |
| 18 | + |
| 19 | +require 'ferret' |
| 20 | + |
| 21 | +class Chef |
| 22 | + class Search |
| 23 | + |
| 24 | + attr_reader :index |
| 25 | + |
| 26 | + def initialize |
| 27 | + @index = Ferret::Index::Index.new(:path => Chef::Config[:search_index_path]) |
| 28 | + end |
| 29 | + |
| 30 | + def search(type, query, attributes, &block) |
| 31 | + search_query = build_search_query(type, query) |
| 32 | + start_time = Time.now |
| 33 | + results = [] |
| 34 | + block ||= lambda { |b| b } |
| 35 | + |
| 36 | + @index.search_each(search_query, :limit => :all) do |id, score| |
| 37 | + results << block.call(build_hash(@index.doc(id))) |
| 38 | + end |
| 39 | + |
| 40 | + Chef::Log.debug("Search #{search_query} complete in #{Time.now - start_time} seconds") |
| 41 | + |
| 42 | + attributes.empty? ? results : filter_by_attributes(results,attributes) |
| 43 | + end |
| 44 | + |
| 45 | + def filter_by_attributes(results, attributes) |
| 46 | + results.collect do |r| |
| 47 | + nr = Hash.new |
| 48 | + nr[:index_name] = r[:index_name] |
| 49 | + nr[:id] = r[:id] |
| 50 | + attributes.each do |attrib| |
| 51 | + if r.has_key?(attrib) |
| 52 | + nr[attrib] = r[attrib] |
| 53 | + end |
| 54 | + end |
| 55 | + nr |
| 56 | + end |
| 57 | + end |
| 58 | + |
| 59 | + private :filter_by_attributes |
| 60 | + |
| 61 | + def list_indexes |
| 62 | + indexes = Hash.new |
| 63 | + @index.search_each("index_name:*", :limit => :all) do |id, score| |
| 64 | + indexes[@index.doc(id)["index_name"]] = true |
| 65 | + end |
| 66 | + indexes.keys |
| 67 | + end |
| 68 | + |
| 69 | + def has_index?(index) |
| 70 | + list_indexes.detect { |i| i == index } |
| 71 | + end |
| 72 | + |
| 73 | + private |
| 74 | + def build_search_query(type, query) |
| 75 | + query = "id:*" if query == '*' |
| 76 | + "index_name:#{type} AND (#{query})" |
| 77 | + end |
| 78 | + |
| 79 | + def build_hash(doc) |
| 80 | + result = Hash.new |
| 81 | + doc.fields.each do |f| |
| 82 | + result[f] = doc[f] |
| 83 | + end |
| 84 | + result |
| 85 | + end |
| 86 | + end |
| 87 | +end |
0 commit comments