Class: ThinkingSphinx::Index

Inherits:
Object
  • Object
show all
Defined in:
lib/thinking_sphinx/index.rb,
lib/thinking_sphinx/index/builder.rb,
lib/thinking_sphinx/index/faux_column.rb

Overview

The Index class is a ruby representation of a Sphinx source (not a Sphinx index - yes, I know it’s a little confusing. You’ll manage). This is another ‘internal’ Thinking Sphinx class - if you’re using it directly, you either know what you’re doing, or messing with things beyond your ken. Enjoy.

Defined Under Namespace

Classes: Builder, FauxColumn

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, &block) ⇒ Index

Create a new index instance by passing in the model it is tied to, and a block to build it with (optional but recommended). For documentation on the syntax for inside the block, the Builder class is what you want.

Quick Example:

Index.new(User) do
  indexes , email

  has created_at

  set_property :delta => true
end


29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/thinking_sphinx/index.rb', line 29

def initialize(model, &block)
  @model        = model
  @associations = {}
  @fields       = []
  @attributes   = []
  @conditions   = []
  @groupings    = []
  @options      = {}
  @delta        = false
  
  initialize_from_builder(&block) if block_given?
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



12
13
14
# File 'lib/thinking_sphinx/index.rb', line 12

def attributes
  @attributes
end

#conditionsObject

Returns the value of attribute conditions.



12
13
14
# File 'lib/thinking_sphinx/index.rb', line 12

def conditions
  @conditions
end

#deltaObject

Returns the value of attribute delta.



12
13
14
# File 'lib/thinking_sphinx/index.rb', line 12

def delta
  @delta
end

#fieldsObject

Returns the value of attribute fields.



12
13
14
# File 'lib/thinking_sphinx/index.rb', line 12

def fields
  @fields
end

#groupingsObject

Returns the value of attribute groupings.



12
13
14
# File 'lib/thinking_sphinx/index.rb', line 12

def groupings
  @groupings
end

#modelObject

Returns the value of attribute model.



12
13
14
# File 'lib/thinking_sphinx/index.rb', line 12

def model
  @model
end

#optionsObject

Returns the value of attribute options.



12
13
14
# File 'lib/thinking_sphinx/index.rb', line 12

def options
  @options
end

Class Method Details

.name(model) ⇒ Object



46
47
48
# File 'lib/thinking_sphinx/index.rb', line 46

def self.name(model)
  model.name.underscore.tr(':/\\', '_')
end

Instance Method Details

#adapterObject



238
239
240
241
242
243
244
245
246
247
# File 'lib/thinking_sphinx/index.rb', line 238

def adapter
  @adapter ||= case @model.connection.class.name
  when "ActiveRecord::ConnectionAdapters::MysqlAdapter"
    :mysql
  when "ActiveRecord::ConnectionAdapters::PostgreSQLAdapter"
    :postgres
  else
    raise "Invalid Database Adapter: Sphinx only supports MySQL and PostgreSQL"
  end
end

#adapter_objectObject



249
250
251
# File 'lib/thinking_sphinx/index.rb', line 249

def adapter_object
  @adapter_object ||= ThinkingSphinx::AbstractAdapter.detect(@model)
end

#delta?Boolean

Flag to indicate whether this index has a corresponding delta index.

Returns:

  • (Boolean)


234
235
236
# File 'lib/thinking_sphinx/index.rb', line 234

def delta?
  @delta
end

#empty?(part = :core) ⇒ Boolean

Returns:

  • (Boolean)


50
51
52
53
# File 'lib/thinking_sphinx/index.rb', line 50

def empty?(part = :core)
  config = ThinkingSphinx::Configuration.instance
  File.size?("#{config.searchd_file_path}/#{self.name}_#{part}.spa").nil?
end

#index_optionsObject



270
271
272
273
274
275
276
# File 'lib/thinking_sphinx/index.rb', line 270

def index_options
  all_index_options = ThinkingSphinx::Configuration.instance.index_options.clone
  @options.keys.select { |key|
    ThinkingSphinx::Configuration::IndexOptions.include?(key.to_s)
  }.each { |key| all_index_options[key.to_sym] = @options[key] }
  all_index_options
end

#infix_fieldsObject



257
258
259
# File 'lib/thinking_sphinx/index.rb', line 257

def infix_fields
  @fields.select { |field| field.infixes }
end

#link!Object

Link all the fields and associations to their corresponding associations and joins. This must be called before interrogating the index’s fields and associations for anything that may reference their SQL structure.



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/thinking_sphinx/index.rb', line 118

def link!
  base = ::ActiveRecord::Associations::ClassMethods::JoinDependency.new(
    @model, [], nil
  )
  
  @fields.each { |field|
    field.model ||= @model
    field.columns.each { |col|
      field.associations[col] = associations(col.__stack.clone)
      field.associations[col].each { |assoc| assoc.join_to(base) }
    }
  }
  
  @attributes.each { |attribute|
    attribute.model ||= @model
    attribute.columns.each { |col|
      attribute.associations[col] = associations(col.__stack.clone)
      attribute.associations[col].each { |assoc| assoc.join_to(base) }
    }
  }
end

#local_index_optionsObject



261
262
263
264
265
266
267
268
# File 'lib/thinking_sphinx/index.rb', line 261

def local_index_options
  @options.keys.inject({}) do |local_options, key|
    if ThinkingSphinx::Configuration::IndexOptions.include?(key.to_s)
      local_options[key.to_sym] = @options[key]
    end
    local_options
  end
end

#nameObject



42
43
44
# File 'lib/thinking_sphinx/index.rb', line 42

def name
  self.class.name(@model)
end

#prefix_fieldsObject



253
254
255
# File 'lib/thinking_sphinx/index.rb', line 253

def prefix_fields
  @fields.select { |field| field.prefixes }
end

#source_optionsObject



278
279
280
281
282
283
284
# File 'lib/thinking_sphinx/index.rb', line 278

def source_options
  all_source_options = ThinkingSphinx::Configuration.instance.source_options.clone
  @options.keys.select { |key|
    ThinkingSphinx::Configuration::SourceOptions.include?(key.to_s)
  }.each { |key| all_source_options[key.to_sym] = @options[key] }
  all_source_options
end

#to_config(model, index, database_conf, offset) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/thinking_sphinx/index.rb', line 55

def to_config(model, index, database_conf, offset)
  # Set up associations and joins
  add_internal_attributes
  link!
  
  attr_sources = attributes.collect { |attrib|
    attrib.to_sphinx_clause
  }.join("\n  ")
  
  db_adapter = case adapter
  when :postgres
    "pgsql"
  when :mysql
    "mysql"
  else
    raise "Unsupported Database Adapter: Sphinx only supports MySQL and PosgreSQL"
  end
  
  config = <<-SOURCE

source #{self.class.name(model)}_#{index}_core
{
type     = #{db_adapter}
sql_host = #{database_conf[:host] || "localhost"}
sql_user = #{database_conf[:username] || database_conf[:user]}
sql_pass = #{(database_conf[:password] || "").gsub('#', '\#')}
sql_db   = #{database_conf[:database]}
#{"sql_port = #{database_conf[:port]}" unless database_conf[:port].blank? }
#{"sql_sock = #{database_conf[:socket]}" unless database_conf[:socket].blank? }

sql_query_pre    = #{utf8? && adapter == :mysql ? "SET NAMES utf8" : ""}
#{"sql_query_pre    = SET SESSION group_concat_max_len = #{@options[:group_concat_max_len]}" if @options[:group_concat_max_len]}
sql_query_pre    = #{to_sql_query_pre}
sql_query        = #{to_sql(:offset => offset).gsub(/\n/, ' ')}
sql_query_range  = #{to_sql_query_range}
sql_query_info   = #{to_sql_query_info(offset)}
#{attr_sources}
#{ThinkingSphinx::Configuration.instance.hash_to_config(self.source_options)}
}
  SOURCE
  
  if delta?
    config += <<-SOURCE

source #{self.class.name(model)}_#{index}_delta : #{self.class.name(model)}_#{index}_core
{
sql_query_pre    = 
sql_query_pre    = #{utf8? && adapter == :mysql ? "SET NAMES utf8" : ""}
#{"sql_query_pre    = SET SESSION group_concat_max_len = #{@options[:group_concat_max_len]}" if @options[:group_concat_max_len]}
sql_query        = #{to_sql(:delta => true, :offset => offset).gsub(/\n/, ' ')}
sql_query_range  = #{to_sql_query_range :delta => true}
}
    SOURCE
  end
  
  config
end

#to_sql(options = {}) ⇒ Object

Generates the big SQL statement to get the data back for all the fields and attributes, using all the relevant association joins. If you want the version filtered for delta values, send through :delta => true in the options. Won’t do much though if the index isn’t set up to support a delta sibling.

Examples:

index.to_sql
index.to_sql(:delta => true)


151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/thinking_sphinx/index.rb', line 151

def to_sql(options={})
  assocs = all_associations
  
  where_clause = ""
  if self.delta?
    where_clause << " AND #{@model.quoted_table_name}.#{quote_column('delta')}" +" = #{options[:delta] ? db_boolean(true) : db_boolean(false)}"
  end
  unless @conditions.empty?
    where_clause << " AND " << @conditions.join(" AND ")
  end
  
  internal_groupings = []
  if @model.column_names.include?(@model.inheritance_column)
     internal_groupings << "#{@model.quoted_table_name}.#{quote_column(@model.inheritance_column)}"
  end
  
  unique_id_expr = "* #{ThinkingSphinx.indexed_models.size} + #{options[:offset] || 0}"
  
  sql = <<-SQL
SELECT #{ (
  ["#{@model.quoted_table_name}.#{quote_column(@model.primary_key)} #{unique_id_expr} AS #{quote_column(@model.primary_key)} "] + 
  @fields.collect { |field| field.to_select_sql } +
  @attributes.collect { |attribute| attribute.to_select_sql }
).join(", ") }
FROM #{ @model.table_name }
  #{ assocs.collect { |assoc| assoc.to_sql }.join(' ') }
WHERE #{@model.quoted_table_name}.#{quote_column(@model.primary_key)} >= $start
  AND #{@model.quoted_table_name}.#{quote_column(@model.primary_key)} <= $end
  #{ where_clause }
GROUP BY #{ (
  ["#{@model.quoted_table_name}.#{quote_column(@model.primary_key)}"] + 
  @fields.collect { |field| field.to_group_sql }.compact +
  @attributes.collect { |attribute| attribute.to_group_sql }.compact +
  @groupings + internal_groupings
).join(", ") }
  SQL
  
  if @model.connection.class.name == "ActiveRecord::ConnectionAdapters::MysqlAdapter"
    sql += " ORDER BY NULL"
  end
  
  sql
end

#to_sql_query_info(offset) ⇒ Object

Simple helper method for the query info SQL - which is a statement that returns the single row for a corresponding id.



198
199
200
201
# File 'lib/thinking_sphinx/index.rb', line 198

def to_sql_query_info(offset)
  "SELECT * FROM #{@model.quoted_table_name} WHERE " +
  " #{quote_column(@model.primary_key)} = (($id - #{offset}) / #{ThinkingSphinx.indexed_models.size})"
end

#to_sql_query_preObject

Returns the SQL query to run before a full index - ie: nothing unless the index has a delta, and then it’s an update statement to set delta values back to 0.



228
229
230
# File 'lib/thinking_sphinx/index.rb', line 228

def to_sql_query_pre
  self.delta? ? "UPDATE #{@model.quoted_table_name} SET #{quote_column('delta')} = #{db_boolean(false)}" : ""
end

#to_sql_query_range(options = {}) ⇒ Object

Simple helper method for the query range SQL - which is a statement that returns minimum and maximum id values. These can be filtered by delta - so pass in :delta => true to get the delta version of the SQL.



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/thinking_sphinx/index.rb', line 207

def to_sql_query_range(options={})
  min_statement = "MIN(#{quote_column(@model.primary_key)})"
  max_statement = "MAX(#{quote_column(@model.primary_key)})"
  
  # Fix to handle Sphinx PostgreSQL bug (it doesn't like NULLs or 0's)
  if adapter == :postgres
    min_statement = "COALESCE(#{min_statement}, 1)"
    max_statement = "COALESCE(#{max_statement}, 1)"
  end
  
  sql = "SELECT #{min_statement}, #{max_statement} " +
        "FROM #{@model.quoted_table_name} "
  sql << "WHERE #{@model.quoted_table_name}.#{quote_column('delta')} " + 
        "= #{options[:delta] ? db_boolean(true) : db_boolean(false)}" if self.delta?
  sql
end