Sphinx Scope Returning Nothing - ruby-on-rails-3

I'm trying to create a simple scope that sphinx will index (Ruby on Rails). The normal scope returns what it should, the sphinx scope returns no results.
define_index do
# fields
indexes :name
indexes author
indexes description
indexes list_of_tags
indexes approved
# attributes
has created_at, updated_at, downloads
# delta indexing
set_property :delta => true
# weighting fields
set_property :field_weights => {
:name => 10,
list_of_tags => 6,
author => 5,
description => 4,
}
end
normal scope:
scope :approved, where(:approved => true)
sphinx scope:
sphinx_scope(:approval_scope) {
{:conditions => {:approved => "true"}}
}
Approved is a boolean field, however, since I'm indexing it as a field, I believe its value is treated as a String. Regardless, letting the value of the sphinx scope be "true" or true makes no difference - Theme.approval_score still returns 0 results unlike Theme.approval. I hope I'm missing something simple..

make the approved with has
define_index do
# fields
...
has approved
...
end
then
sphinx_scope(:approval_scope) {
{:with => {:approved => true}}
}

Related

ElasticSearch Tire two field conditional filter

I'm doing a mutli-index query With Tire and rails 3 and I want to filter out Venues who have approved => false so I need some sort of combo filter.
Here is the query
query = params[:q]
from = params.delete(:from)
size = params[:size] || 25
Tire.search(
[Venue.index_name,
Performer.index_name, User.index_name], load: true) do |s|
s.query do
string(query, fields: [:_all, :name, :title], use_dis_max: true)
end
s.from from if from
s.size size if size
end.results.to_a
This line removes all Performers and Users because they don't have an :approved field.
s.filter(:term, :approved => true )
And this line obviously removes all non-venues which is no good.
s.filter(:term, { :approved => true, :index_name => 'venues'} )
Any ideas besides adding an approved: true field to all Users and Performers? I think something like this is what I want conceptually:
s.filter(:term, :approved => true, :if => {:index_name => 'venues'} )
EDIT Thanks to Mallox I was able to find the Should construct but I'm still struggling to implement it Tire. It seems like the below code should work but it return no results on any query. I also remove the "{:terms => { :index_name => ["performers", "users"]}}," to make sure it wasn't my use of index name or multiple lines of query that was the problem and still no luck. Can anybody shed some light on how to do this in Tire?
s.filter(:bool, :should => [
{:terms => { :index_name => ["performers", "users"]}},
{:term => { :approved => true}},
] )
So i have little knowledge about Ruby and Tire, but the ElasticSearch query that you want to build would be based on a bool filter, that contains some "should" entries (which would translate into inclusive OR).
So in your case something along the lines of:
"filter" : {
"bool" : {
"should" : [
{
"terms" : { "_type" : ["Performers","Users"] }
},
{
"term" : { "approved" : true }
}
]
}
}
Take a look at the documentation here, maybe that'll help:
:http://www.elasticsearch.org/guide/reference/query-dsl/bool-filter/

sphinxql: syntax error, unexpected IDENT

Getting this error with sphinx 2
sphinxql: syntax error, unexpected IDENT, expecting CONST_INT or CONST_FLOAT or '-' near 'WI AND published = 1 AND sphinx_deleted = 0 LIMIT 0, 10; SHOW META'
index.html.erb
error is being thrown in the template at the line of a partial collection: #posts_by_state, but two other instances of the same partial are working great. The State sort is what is throwing it off.
posts_controller.rb
#posts_by_state = Post.search(params[:search], with: { state: current_user.state, published: true }, :page => params[:page], :per_page => 10)
post_index.rb
ThinkingSphinx::Index.define :post, :with => :active_record do
indexes :title, as: :post_title
indexes :desc, as: :description
indexes tags(:name), as: :tag_name
#indexes happening_on, sortable: true
#has author_id, published_at
has published_at
has last_touched
has state
has published
set_property:field_weights => {
:post_title => 5,
:description => 1,
:tag_name => 10
}
end
String attributes in Sphinx can only be used for sorting - not filtering, not grouping - and so your options to work around this are as follows:
Pull it out into an associated model (State or PostState, perhaps?), and then filter by the foreign key integer instead.
Store that value as a field instead, and use :conditions instead of :with.
Hack around it with CRC32 values.
I highly recommend the first of these options (I'd argue it's cleaner, accurate), but it's up to you.

How to filter IS NULL in ActiveAdmin?

I've a table with an integer column called "map_id", I want to add an activeadmin filter to filter if this column IS NULL or IS NOT NULL.
How could this be implemented ?
I tried the following filter
filter :map_id, :label => 'Assigned', :as => :select, :collection => {:true => nil, :false => ''}
But, I get the following error message :
undefined method `map_eq' for #
If anyone is happening on this thread belatedly, there is now an easy way to filter for null or non null in active admin :
filter :attribute_present, :as => :boolean
filter :attribute_blank, :as => :boolean
It is no longer necessary to add a custom method to the scope to accomplish this.
Not found a good solution but here is a how.
filters of Active_admin are accomplished by meta_search, you can override the functions automatically generated by meta_search in your model to get the behavior that you want, the best way is to use the scope since you need to return a relation in order to chain with other query/scopes, as stated here
in your model:
for :as=>:select filters, acitve_admin use the _eq wheres, here is the source code
scope :map_eq,
lambda{ |id|
if(id !='none')
where( :map_id=> id)
else
where( :map_id=> nil)
end
}
#re-define the search method:
search_method :map_eq, :type => :integer
in your ative_admin register block:
filter :map_id, :label => 'Assigned', :as => :select, :collection => [['none', 'none'], ['one', 1],['tow', 2]]
# not using :none=>nil because active_admin will igore your nil value so your self-defined scope will never get chained.
Hope this help.
seems search_method doesn't work in recent rails version, here is another solution:
add scope to your model:
scope :field_blank, -> { where "field is null" }
scope :field_not_blank, -> { where "field is not null" }
add to /app/admin/[YOUR MODEL]
scope :field_blank
scope :field_not_blank
you will see buttons for these scopes appear (in top section, under model name, not in filter section)
The new version of ActiveAdmin uses Ransacker. I manage to got it working this way:
On the admin
filter :non_nil_map_id, :label => 'Assigned', :as => :select, :collection => [['none', 'none'], ['one', 1],['tow', 2]]
For consistency, I took the same code from #Gret answer just changing the filter name
On your model
ransacker :not_nil_map_id, :formatter => proc {|id| map_id != 'none' ? id : 'none' } do |parent|
parent.table[:id]
end
This should trigger a search against nil in case the id is 'none', and active record will return all the nil id entries.
This thread helped a lot.
With ransackable scopes:
On the ActiveAdmin resource definition:
filter :map_id, :label => 'Assigned', as: :select, :collection => [['Is Null', 'none'], ['Not null', 'present']]
On your model:
scope :by_map_id, ->(id) { (id == 'none' ? where(map_id: nil) : where('map_id IS NOT NULL')) }
def self.ransackable_scopes(_auth_object = nil)
%i[by_map_id]
end

How can I get an ActiveRecord query to ignore nil conditions?

In order to avoid having to construct complicated dynamic SQL queries, I'd like to be able to just pass in nil values in my conditions, and have those ignored. Is that supported by ActiveRecord?
Here is an example.
event = Event.find(:all, :conditions => {
:title => params[:title],
:start_time => params[:start_time],
:end_time => params[:end_time]
}).first
In that particular case, if params[:start_time] is set to nil, ActiveRecord will search for those Events that have their start_time set to null. Instead, I'd like it to just ignore start_time. How do I do that?
You don't have to "create complicated dynamic SQL queries" to do what you need. Simply construct your conditions hash separately, and either exclude the null values at the time of creation or after you've created the hash.
conditions = {}
conditions[:title] = params[:title] unless params[:title].blank?
conditions[:start_time] = params[:start_time] unless params[:start_time].blank?
conditions[:end_time] = params[:end_time] unless params[:end_time].blank?
or
conditions = {:title => params[:title], :start_time => params[:start_time], :end_time => params[:end_time]}
conditions.delete_if {|k,v| v.blank? }
or
conditions = params.reject {|k,v| !([:title, :start_time, :end_time]).include?(k) }
but that last form will only work if the keys are actually symbols. In Rails the params hash is a HashWithIndifferentAccess which allows you to access the text keys as symbols. Of course you could just use the text values in your array of keys to include if necessary.
and then query with your pre-built conditions hash:
event = Event.find(:all, :conditions => conditions).first

How to use MongoID validates_inclusion_of

I have a model with a field that can contain a list of values. I want that list to be limited to a subset. I want to use validates_inclusion_of, but probably misunderstand that validation.
class Profile
include Mongoid::Document
field :foo, :type => Array
validates_inclusion_of :foo, in: %w[foo bar]
end
p = Profile.new
p.valid? #=> false; this is correct, as it should fail on empty lists.
p.foo = ["bar"]
p.valid? #=> false; this is incorrect. I would expect it to pass now.
p.errors #=> {:foo=>["is not included in the list"]}
What am I doing wrong? Can validates_inclusion_of be used for arrays?
Your field value is an array (field :foo, :type => Array)
Validation expects field to be not an array to check its inclusion.
By your example validation is checking for ['foo', 'bar'].include?(['bar']) # => false
So correct your :in option in validates_inclusion_of:
validates_inclusion_of :foo, in: [['foo'], ['bar']]