O slideshow foi denunciado.
Seu SlideShare está sendo baixado. ×

BigData - ElasticSearch + PHP

Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio

Confira estes a seguir

1 de 22 Anúncio

Mais Conteúdo rRelacionado

Diapositivos para si (20)

Semelhante a BigData - ElasticSearch + PHP (20)

Anúncio

Mais recentes (20)

BigData - ElasticSearch + PHP

  1. 1. BigData Indexando e buscando dados com ElasticSearch e PHP Felipe Weckx
  2. 2. PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 2/22 Agenda ● ElasticSearch ● PHP + ElasticSearch ● Lições Aprendidas
  3. 3. PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 3/22 ElasticSearch ● Busca e análise de dados ● Gratuito e Open Source ● Desenvolvido em Java ● Comunidade ativa ● Excelente documentação ● Fácil de instalar e configurar ~ $ tar xzf elasticsearch-1.4.1.tar.gz ~ $ ./elasticsearch-1.4.1/bin/elasticsearch
  4. 4. PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 4/22 Para que usar? ● Complemento da base de dados ● Buscas FULLTEXT e complexas ● Estruturas de dados simples ● Análise estatística
  5. 5. PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 5/22 ElasticSearch - Conceitos ● Índices → Tipos → Documentos ● Schema-less – documentos JSON ● Internamente utiliza Lucene ● TODOS os campos são indexados – Indexação utilizando “Índice Reverso” ● Interface através de API RESTful
  6. 6. Índice Tipo ID PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 6/22 Indexando ~ $ curl -XPUT localhost:9200/phpconference/palestras/1 -d '{ titulo : "Palestra BigData ", data : "2014-12-05", tags : [ "bigdata", "elasticsearch", "php"] }' localhost:9200/phpconference/palestras/1
  7. 7. PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 7/22 Consultando ~ $ curl -XGET localhost:9200/phpconference/palestras/1?pretty { "_index" : "phpconference", "_type" : "palestras", "_id" : "1", "_version" : 1, "found" : true, "_source":{ titulo : "Palestra BigData ", data : "2014-12-05", tags : [ "bigdata", "elasticsearch", "php"] } }
  8. 8. PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 8/22 Rivers ● Plugins ● Sincronização automática com outras fontes – JDBC (MySQL, Oracle, PostgreSQL, etc) – MongoDB – Twitter – … ● Úteis para integração rápida, mas podem não ser a melhor solução
  9. 9. PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 9/22 Escalando ● Escalonamento automático ● Operações podem ser feitas em qualquer nó ● Shard = base de busca independente ● Configuração por Índice – Quantidade de shards – Quantidade de réplicas
  10. 10. PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 10/22 ElasticSearch + PHP ● Biblioteca oficial – PHP >= 5.3.9 – ConnectionPool – Instalação simples com Composer ● Alternativas* – php-curl – php-http * Requisições manuais { "require": { "elasticsearch/elasticsearch": "~1.0" } }
  11. 11. PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 11/22 Configuração Client PHP <?php $params = array( 'hosts' => [ '192.168.1.6:9200', '192.168.1.7', //Porta padrão 9200 'https://192.168.1.8' ] ); $client = new ElasticsearchClient($params); ● Um dos hosts da lista é sorteado aleatoriamente ● ConnectionPool interna mantém status dos hosts ● Pode descobrir hosts automaticamente através de sniffing
  12. 12. PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 12/22 Indexando com PHP $document = array( 'index' => 'phpconference', 'type' => 'palestras', 'body' => array( 'titulo' => 'A future without frameworks', 'data' => '2015-12-05' ) ); $response = $client->index($document); $id = $response['_id']; //ID gerado automaticamente echo 'Indexado ' . $id ;
  13. 13. PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 13/22 Busca – Query String $params['index'] = 'phpconference'; $params['type'] = 'palestras'; $params['body'] = [ 'query' => [ 'query_string' => [ 'query' => 'future' ] ] ]; $results = $client->search($params);
  14. 14. PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 14/22 Query Strings - Exemplos ● assunto:”bigdata” AND data:”2014-12-05” ● palestrante:felipe OR palestrante:diego ● data:>2014-12-05 – Documentos com data > 05/12/2014 ● elasticsearch +php -java – Buscar por ElasticSearch, deve conter o termo “php” e não o termo “java”
  15. 15. PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 15/22 Queries vs Filtros ● Queries – Utilizar buscas aproximadas – Retorna score dos resultados – Sem cache ● Filtros – Cache! – Utilizar para buscas do tipo sim/não – Podem ser usados em conjunto com queries
  16. 16. PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 16/22 Busca Composta $params['body'] = [ 'query' => [ 'filtered' => [ 'query' => [ 'term' => [ 'titulo' => 'fut*' ] ], 'filter' => [ 'match' => [ 'data' => '2014-12-05'] ] ] ];
  17. 17. PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 17/22 Aggregations ● Parte da funcionalidade de busca ● Permite fazer agrupamentos e métricas ● Agrupamentos podem ser retornados junto com os resultados – Para evitar: search_type = count ● Múltiplos agrupamentos na mesma requisição
  18. 18. PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 18/22 Aggregations $params['body'] = [ 'query' => [ 'match_all' => new stdClass() ], 'aggs' => [ 'palestras_por_data' => [ 'date_histogram' => [ 'field' => 'data', 'interval' => 'day' ] ], 'palestras_por_palestrante' => [ 'terms' => ['field' : 'palestrante' ] ] ] ];
  19. 19. PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 19/22 Aggregations - Resultado "palestras_por_data":{ "buckets":[ { “key_as_string":"2014-12-05T00:00:00.000Z", "key":1417737600000, "doc_count":10 }, ... ], "palestras_por_palestrante":{ "buckets":[ { "key":"felipe", "doc_count":2 }, ]}
  20. 20. PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 20/22 Aprendizado ● Objeto vazio = new stdClass(); ● Quanto mais memória no servidor, melhor – Necessário configurar no ElasticSearch – Cuidado com estouro de HEAP no Java ● Quando possível separar dados em mais de um índice – Ex: um índice por dia para histórico de eventos
  21. 21. PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 21/22 Perguntas?
  22. 22. PHP Conference 2014 BigData – ElasticSearch + PHP Felipe Weckx 22/22 Obrigado! Felipe Weckx felipe@weckx.net @weckx github.com/weckx linkedin.com/in/felipeweckx http://blog.weckx.net

×