Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Elasticsearch - Turbinando sua aplicação PHP
Search
Breno Oliveira
March 21, 2016
Programming
1
150
Elasticsearch - Turbinando sua aplicação PHP
Utilizando Elasticsearch em suas aplicações PHP
Breno Oliveira
March 21, 2016
Tweet
Share
More Decks by Breno Oliveira
See All by Breno Oliveira
Spring e Eureka Service Discovery
brenooliveira
0
53
Como Fazer Minha Gem e o Rails Conversarem Bem
brenooliveira
0
42
Javascript Pitfalls
brenooliveira
0
83
Elasticsearch
brenooliveira
1
120
Falando sobre testes automatizados
brenooliveira
0
83
Other Decks in Programming
See All in Programming
WebフロントエンドにおけるGraphQL(あるいはバックエンドのAPI)との向き合い方 / #241106_plk_frontend
izumin5210
4
1.4k
Nurturing OpenJDK distribution: Eclipse Temurin Success History and plan
ivargrimstad
0
890
ActiveSupport::Notifications supporting instrumentation of Rails apps with OpenTelemetry
ymtdzzz
1
230
광고 소재 심사 과정에 AI를 도입하여 광고 서비스 생산성 향상시키기
kakao
PRO
0
170
Tauriでネイティブアプリを作りたい
tsucchinoko
0
370
AWS IaCの注目アップデート 2024年10月版
konokenj
3
3.3k
リアーキテクチャxDDD 1年間の取り組みと進化
hsawaji
1
220
NSOutlineView何もわからん:( 前編 / I Don't Understand About NSOutlineView :( Pt. 1
usagimaru
0
330
Kaigi on Rails 2024 〜運営の裏側〜
krpk1900
1
200
3 Effective Rules for Using Signals in Angular
manfredsteyer
PRO
0
110
CSC509 Lecture 11
javiergs
PRO
0
180
距離関数を極める! / SESSIONS 2024
gam0022
0
280
Featured
See All Featured
How to Create Impact in a Changing Tech Landscape [PerfNow 2023]
tammyeverts
47
2.1k
Teambox: Starting and Learning
jrom
133
8.8k
Why You Should Never Use an ORM
jnunemaker
PRO
54
9.1k
Imperfection Machines: The Place of Print at Facebook
scottboms
265
13k
Building an army of robots
kneath
302
43k
The Myth of the Modular Monolith - Day 2 Keynote - Rails World 2024
eileencodes
16
2.1k
The Art of Delivering Value - GDevCon NA Keynote
reverentgeek
8
860
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
31
2.7k
Raft: Consensus for Rubyists
vanstee
136
6.6k
Exploring the Power of Turbo Streams & Action Cable | RailsConf2023
kevinliebholz
27
4.3k
Sharpening the Axe: The Primacy of Toolmaking
bcantrill
38
1.8k
The World Runs on Bad Software
bkeepers
PRO
65
11k
Transcript
Breno Oliveira @brenoholiveira
[email protected]
B R E N O O
L I V E I R A Tech Leader at Moip ElasticSearch Turbinando sua aplicação PHP
None
+ 86k de contas vendendo
+ 100K de pedidos por dia
None
None
VENDAS AUMENTAM VENDEDOR QUER SABER
None
Ordenação FullText Search Paginação Agregação Filtros
REALTIME
E O SEU SERVER DEPOIS DE VÁRIOS F5 …
None
None
NOSSA VONTADE É DE …
SEU CLIENTA VAI…
PHP + MySQL PHP + postgresql PHP + nosql PHP
+ ????
CASO DE USO
+
502 200 304
+
Aplicação MOIP Base de Dados Master
Single Term SELECT * FROM pedidos p INNER JOIN cliente
ON p.cliente_id = c.id WHERE p.descricao LIKE "%superman%"
multi Term SELECT * FROM pedidos p INNER JOIN cliente
ON p.cliente_id = c.id WHERE p.descricao LIKE "%superman%" OR p.descricao LIKE "%batman%"
ORDER ARRGH!!!! SELECT * FROM pedidos p INNER JOIN cliente
ON p.cliente_id = c.id WHERE p.descricao LIKE "%superman%" OR p.descricao LIKE "%batman%" ORDER BY ??
PROBLEMAS • Difícil manter • Muitos JOINS • Lento
.Primeiro REFACTOR
MICRO SERVIÇO + BANCO denormalizado
APLICAÇÃO MOIP Base de Dados Master REPORTS API Base de
Dados denormalizada
MELHORIAS • Micro serviço • Concorrência no banco de dados
• No more JOINS • Full-Text Search • Melhorias de desempenho
PROBLEMAS • Periodos longos • Filtros • Lentidão
.SEgundo REFACTOR
MICRO SERVIÇO + Banco colunar
APLICAÇÃO MOIP Base de Dados Master REPORTS API
MELHORIAS • Consultas significantemente mais rápidas
PROBLEMAS • BULK INSERTs Too Slow
.terceiro REFACTOR
MICRO SERVIÇO + Elasticseach
APLICAÇÃO MOIP Base de Dados Master REPORTS API Elasticsearch
MELHORIAS • Bulk INSERT • Desempenho • Aggregations • Scalable
• Redundancy
.Atualmente
None
Last Black Friday
None
None
None
.não é banco da dados
.nem nosql I T ' ’ N O T K
E Y- VA L U E S T O R A G E
.Escalável
.Alta resiliencia
.restful api
.orientado a documentos
.full-text search
.free schema
.Eventualmente consistente
.apache lucene
None
.Conceitos básicos Elasticsearch
MySQL Elasticsearch Database Index Table Type Column Field Schema Mapping
Partition Shard
curl -XPUT http://localhost:9200/tips/tip/1 -d '{"tip": "Using Elasticsearch in Production", "tags":
["protip","success"]} ' Endpoint Index Type Document ID Document { "_index": "tips", "_type": "tip", "_id": "1", "_version": 1, "created": true } Response
$ curl http://localhost:9200/tips/tip/1?pretty { "_index": "tips", "_type": "tip", "_id": "1",
"_version": 1, "found": true, "_source": { "tip": "Using Elasticsearch in Production", "tags": [ "protip", "success" ] } }
None
VAGRANT
$ git clone
[email protected]
:brenooliveira/elastic-php-demo.git $ cd elastic-php-demo $ vagrant up
—provision $ vagrant ssh vagrant@default:~/$
vagrant@default:$ curl http://localhost:9200 { "status" : 200, "name" : "Corruptor",
"cluster_name" : "elasticsearch", "version" : { "number" : "1.5.2", "build_hash" : "62ff9868b4c8a0c45860bebb259e21980778ab1c", "build_timestamp" : "2015-04-27T09:21:06Z", "build_snapshot" : false, "lucene_version" : "4.10.4" }, "tagline" : "You Know, for Search" }
{ "require": { "elasticsearch/elasticsearch": "~2.0@beta" } } composer.json $ curl
-s http://getcomposer.org/installer | php $ php composer.phar install --no-dev
<?php require 'vendor/autoload.php'; $client = Elasticsearch\ClientBuilder::create() ->build(); $params = array();
$params['index'] = 'tips'; $params['type'] = 'tip'; $params['id'] = '1'; $result = $client->get($params) ?> <pre> <?= print_r($result); ?> </pre> exemplo1.php
Array ( [_index] => tips [_type] => tip [_id] =>
1 [_version] => 1 [found] => 1 [_source] => Array ( [tip] => Using Elasticsearch in Production [tags] => Array ( [0] => protip [1] => success ) ) )
exemplo2.php <?php require 'vendor/autoload.php'; $client = Elasticsearch\ClientBuilder::create() ->build(); $params =
[ 'index' => 'tips', 'type' => 'tip', 'id' => '2', 'body' => [ 'tip' => 'Using Marvel to get metrics from Elasticsearch', 'tags' => ['protip', 'metrics'] ] ]; // Documento indexado em tips/tip/2 $response = $client->index($params); ?> <pre> <?= print_r($response) ?> </pre>
exemplo3.php <?php require 'vendor/autoload.php'; $client = Elasticsearch\ClientBuilder::create() ->build(); for($i =
0; $i < 100; $i++) { $params['body'][] = [ 'index' => [ '_index' => 'jobs', '_type' => 'job', ] ]; $params['body'][] = [ 'title' => 'Job position '. $i, 'email' => 'email-'. $i . '@gmail.com' ]; } $responses = $client->bulk($params); ?>
exemplo4.php <?php require 'vendor/autoload.php'; $client = Elasticsearch\ClientBuilder::create()->build(); $json = '{
"query" : { "match" : { "tags" : "protip" } } }'; $params = [ 'index'=> 'tips', 'type' => 'tip', 'body' => $json ]; $responses = $client->search($params); ?> <pre> <?= print_r($responses) ?> </pre>
exemplo5.php <?php require 'vendor/autoload.php'; $client = Elasticsearch\ClientBuilder::create()->build(); $params = [
'index' => 'tips', 'type' => 'tip', 'id' => '3', 'body' => [ 'tip' => 'Wrong insert', 'tags' => ['missing', 'error', 'no_logs'] ] ]; $response_insert = $client->index($params); $params = [ 'index' => 'tips', 'type' => 'tip', 'id' => '3' ]; $responde_delete = $client->delete($params); ?>
exemplo6.php <?php require 'vendor/autoload.php'; $client = Elasticsearch\ClientBuilder::create()->build(); $params = [
'index' => 'tips', 'type' => 'tip', 'id' => '4', 'body' => [ 'tip' => 'Loren Ipsum', 'tags' => ['lorem'] ] ]; $response_insert = $client->index($params); $params = [ 'index' => 'tips', 'type' => 'tip', 'id' => '4', 'body' => [ 'doc' => [ 'text' => 'lipsum generator' ] ] ]; $response_update = $client->update($params); $params = [ 'index' => 'tips', 'type' => 'tip', 'id' => '4' ]; $response_search = $client->get($params); ?>
exemplo7.php <?php require 'vendor/autoload.php'; $client = Elasticsearch\ClientBuilder::create()->build(); $json = '{
"my-suggestion" : { "text" : "Elastiscearch", "term" : { "field" : "tip" } } }'; $params = [ 'index' => 'tips', 'body' => $json ]; $response = $client->suggest($params); ?>
exemplo8.php <?php require 'vendor/autoload.php'; $client = Elasticsearch\ClientBuilder::create()->build(); $json = '{
"query" : { "more_like_this" : { "like_text" : "In production", "min_term_freq" : 1, "min_doc_freq" : 1 } } }'; $params = [ 'index' => 'tips', 'type' => 'tip', 'body' => $json ]; $response = $client->search($params); ?>
.Vamos falar de arquitetura
.Como devo sincronizar mysql & Elasticsearch
E-commerce app Base de Dados Elasticsearch Cadastrar novo produto
E-commerce app Base de Dados Elasticsearch rabbitmq Publish Message php
worker Consume Message & Sync Cadastrar novo produto
.Lessons learned
Utilize mais mappings
Em produção use alias
None