ElasticSearch

08 Apr 2015, by

简单安装

sudo add-apt-repository ppa:webupd8team/java
sudo apt
-get update
sudo apt
-get install oracle-java8-installer

基本概念

Relational DB(一般是以文档ID作为索引,以文档内容作为记录。) -> Databases(数据库) -> Tables(表) -> Rows(行) -> Columns(列)
Elasticsearch(倒排索引将单词或记录作为索引,将文档ID作为记录) -> Indices(索引)   -> Types(类型)  -> Documents(文档) -> Fields(字段)

基本命令

参考资料

elasticsearch-rails

def as_indexed_json(options={})
   
{
      title
: title,
      product_categories
:   product_categories.as_json(only: [:describe]),
      categories
: categories.map(&:name)
   
}
   
# self.as_json(
   
#   include: {
   
#     product_details: {
   
#       only: :describe
   
#     }
   
#   },
   
#   categories: categories.map(&:name)
   
# )
 
end

 
def as_indexed_json(options={})
    as_json
(
      only
: [:id, :full_name, :email],  # mysql字段
      include
: [:phone_numbers],
      methods
: [:full_name]  # 虚拟属性
   
)
 
end
search(
        query
: {
         
bool: {
            should
: [
             
{
                nested
: {
                  path
: 'product_details',
                  query
: {
                   
bool: {
                      must
: [
                       
{ match: { 'product_details.describe' => q } }
                     
]
                   
}
                 
}
               
}
             
},
            filtered
: {
              query
: {
                multi_match
: {
                  fields
: ['title'],
                  query
: q
               
}
             
},
              filter
: {
                terms
: {
                  categories
: category.split
               
}
             
}
           
}
         
]
       
}
     
})
module ArticleImport
 
def self.import
   
Article.includes(:author, :tags).find_in_batches do |articles|
      bulk_index
(articles)
   
end
 
end

 
def self.prepare_records(articles)
    articles
.map do |article|
     
{ index: { _id: article.id, data: article.as_indexed_json } }
   
end
 
end

 
def self.bulk_index(articles)
   
Article.__elasticsearch__.client.bulk({
      index
: ::Article.__elasticsearch__.index_name,
      type
: ::Article.__elasticsearch__.document_type,
      body
: prepare_records(articles)
   
})
 
end
end