dockerãç¨ããRailsã®éçºç°å¢ã«æ°ãã«Elasticsearhãçµã¿è¾¼ãã ã®ã§ã¾ã¨ãã¾ãã
Dockerã®è¨å®
docker-compose.ymlã以ä¸ã®ããã«ä¿®æ£ãã¾ãã
version: '2' services: rails: # ~ imageã¨ãå ã ã®è¨å®ï¼çç¥ï¼ ~ # 追å depends_on: - elasticsearch # 追å elasticsearch: image: elasticsearch:5.6.10 # 追å kibana: image: kibana ports: - 5601:5601 depends_on: - elasticsearch
Elasticsearchãåãã³ã³ããã追å ãã¦ãdepends_on
ã§èµ·åé ãå¶å¾¡ãã¦ãã¾ãã
kibanaãå ¥ãã¦ãã¾ãããã©ã¦ã¶ä¸ã§æä½ã»ç¢ºèªãããããããã§ãã
Railså´ã®è¨å®
gemã追å
ç¶ãã¦Gemfileã«elasticseachç¨ã®gemã追å ãã¾ãã使ãgemã¯ãã¡ãã§ãã
以ä¸ãGemfileã«è¨è¿°ãã¾ãã
gem 'elasticsearch-model', git: 'https://github.com/elasticsearch/elasticsearch-rails.git', branch: "5.x" gem 'elasticsearch-rails', git: 'https://github.com/elasticsearch/elasticsearch-rails.git', branch: "5.x"
bundle install
branch: "5.x"
ã§ãã¼ã¸ã§ã³ãæå®ãã¦ããã®ã«æ³¨æãã¦ä¸ãããelasticsearchãä»å5ç³»ãå
¥ãã¦ããããgemã®ãã¼ã¸ã§ã³ã5ç³»ã«åããã¦ãã¾ãããããåãããªãã¨åãã¾ãããæå6.xã¨5.xã®çµã¿åããã§ãããã¾ããã詳ããã¯ãã¡ãã
File: README — Documentation for elasticsearch-model (5.1.0)
è¨å®ãã¡ã¤ã«ã追å
config/initializers/elasticsearch.rb
ãç¨æãã以ä¸ãè¨è¿°ãã¾ãã
Elasticsearch::Model.client = Elasticsearch::Client.new hosts: [ { host: 'elasticsearch', port: '9200' } ]
ãã®ãã¡ã¤ã«ã§æ¥ç¶ããããã®hostã¨portãæå®ãã¾ããdocker-composeã§ä½æãããããhostã¯ã³ã³ããåã¨åãelasticsearch
ã§OKã§ãã詳ããã¯å²æãã¾ãããDNSãå
é¨çã«ä½ãã解決ãã¦ããã¦ãã¾ããportã¯ããã©ã«ãã§9200ã§ãã
Modelã«çµã¿è¾¼ã
å®éã«Elasticsearchãæ±ãModelã«è¨è¿°ãã¦ããã¾ããä»åã¯ä¾ã¨ãã¦Bookã¯ã©ã¹ã«è¨è¿°ãã¾ãã
require 'elasticsearch/model' # 追å class Book include Elasticsearch::Model # 追å end
å®éã«åããã¦ã¿ã
ããã§å¿
è¦æä½éã®æºåãæ´ãã¾ãããrails console
ã§ãã¼ã¿ã®å
¥ãè¾¼ã¿ããã¦ã¿ã¾ãã
docker-compose run rails rails c [1] pry(main)> Book.__elasticsearch__.create_index! # ã¤ã³ããã¯ã¹ãä½ããã [2] pry(main)> Book.__elasticsearch__.import # å ã®DBï¼mysqlãªã©ï¼ãã1000件ãã¤å ¨ãã¼ã¿ãåã£ã¦ãã¦insertãã
Elasticsearch::Model
ãincludeãããã¨ã§ä¸è¨ã®ã¡ã½ããã使ããããã«ãªãããã¼ã¿ã®ä½æãã§ãã¾ãã
試ãã«æ¤ç´¢ããã¦ã¿ã¾ãã
[3] pry(main)> Book.__elasticsearch__.search(query: {match_all: {}}).records.to_a => [(Bookã¯ã©ã¹ã®ã¤ã³ã¹ã¿ã³ã¹ã®é åâ¦)] # å ¨ä»¶åå¾ï¼elasticsearchã®ããã©ã«ãè¨å®ã«ãã10件ï¼ãããBookã¢ãã«ã®ã¤ã³ã¹ã¿ã³ã¹ãåãã [4] pry(main)> Book.__elasticsearch__.search(query: { match: { name: "hoge" } }).records.to_a => [(Bookã¯ã©ã¹ã®ã¤ã³ã¹ã¿ã³ã¹ã®é åâ¦)] # nameã«"hoge"ãå«ã¾ãããã¼ã¿ãåå¾
__elasticsearch__.search
ã¡ã½ããã®å¼æ°ã«Elasticsearchã®ã¯ã¨ãªãå
¥åãããã¨ã§æ¤ç´¢ãã§ãã¾ããããã§æä½éã®ç°å¢ãæãããã¨ãã§ãã¾ããã
localhost:5061
ã«ã¢ã¯ã»ã¹ãããã¨ã§kibanaä¸ã§ç¢ºèªãããã¨ãã§ãã¾ãã
ã¾ãä»åº¦ã¯ãªã¬ã¼ã·ã§ã³å ã®ãã¼ã¿ãimportããæã®è¨å®ãªã©ãã¾ã¨ãããã¨æãã¾ããã§ã¯ã
Elasticsearchå®è·µã¬ã¤ã (impress top gear)
- ä½è : æ£éå²ä¹
- åºç社/ã¡ã¼ã«ã¼: ã¤ã³ãã¬ã¹
- çºå£²æ¥: 2018/06/15
- ã¡ãã£ã¢: åè¡æ¬ï¼ã½ããã«ãã¼ï¼
- ãã®ååãå«ãããã°ãè¦ã