Skip to content

Instantly share code, notes, and snippets.

@Rio517
Created September 10, 2012 21:37
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 Rio517/3694072 to your computer and use it in GitHub Desktop.
Save Rio517/3694072 to your computer and use it in GitHub Desktop.
ElasticSearch Sandbox - a little ruby script to give me a place to test out ElasticSearch facets and queries.
require 'tire'
require 'sqlite3'
require 'active_record'
ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: ":memory:" )
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define(version: 1) do
create_table :articles do |t|
t.string :title
t.integer :readers
end
create_table :comments do |t|
t.string :author
t.text :body
t.references :article
end
end
class Comment < ActiveRecord::Base
belongs_to :article
end
class Article < ActiveRecord::Base
has_many :comments
include Tire::Model::Search
include Tire::Model::Callbacks
settings :number_of_shards => 1,
:number_of_replicas => 1,
:analysis => {
:filter => {
:url_ngram => {
"type" => "nGram",
"max_gram" => 5,
"min_gram" => 3 }
},
:analyzer => {
:url_analyzer => {
"tokenizer" => pattern: {pattern: '$'},
"filter" => [],
"type" => "custom" }
}
} do
mapping do
indexes :title, type: 'string'
indexes :readers, type: 'integer'
indexes :comments do
indexes :author, type: 'string', :analyzer => :url_analyzer
indexes :body, type: 'string', :analyzer => :url_analyzer
end
end
end
self.include_root_in_json = false
def to_indexed_json
to_json(include: :comments)
end
end
Article.destroy_all
Article.index.delete
Article.index.create
article = Article.new title: 'First article', readers: 1
article.comments.build body: 'Awesome article!', author: 'Red Fox'
article.save
article = Article.create! title: 'second article', readers: 20
article.comments.create! body: 'Shit article!', author: 'Red Wolf'
article = Article.new title: 'Third article', readers: 300
article.comments.new body: 'Ok article!', author: 'Blue Wolf'
article.save
article = Article.new title: 'Fourth article', readers: 4000
article.comments.build body: 'Really Ok article!', author: 'Blue Wolf'
article.save
article.index.refresh
s = Article.tire.search do
query { all }
facet('terms_facet') do
terms_stats 'comments.author', :readers
end
end
s.facets.each{|k,v| p v['terms'].collect{|e| e['term'] }.join(',') }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment