BigData - ElasticSearch + PHP

22
BigData Indexando e buscando dados com ElasticSearch e PHP Felipe Weckx

description

Palestra apresentada na PHP Conference 2014. Introdução ao ElasticSearch, com sua configuração, conceitos e uso. Exemplos de uso do API com o PHP e melhores práticas.

Transcript of BigData - ElasticSearch + PHP

Page 1: BigData - ElasticSearch + PHP

BigDataIndexando e buscando dados com ElasticSearch

e PHP

Felipe Weckx

Page 2: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe Weckx

2/22

Agenda

● ElasticSearch● PHP + ElasticSearch● Lições Aprendidas

Page 3: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe 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

Page 4: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe Weckx

4/22

Para que usar?

● Complemento da base de dados● Buscas FULLTEXT e complexas● Estruturas de dados simples● Análise estatística

Page 5: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe 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

Page 6: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe 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

Índice Tipo ID

Page 7: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe 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"] }}

Page 8: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe 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

Page 9: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe 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

Page 10: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe 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"    }}

Page 11: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe 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 Elasticsearch\Client($params);

● Um dos hosts da lista é sorteado aleatoriamente● ConnectionPool interna mantém status dos hosts● Pode descobrir hosts automaticamente através de sniffing

Page 12: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe 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 automaticamenteecho 'Indexado ' . $id ;

Page 13: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe Weckx

13/22

Busca – Query String

$params['index'] = 'phpconference';

$params['type'] = 'palestras';

$params['body'] = [

'query' => [

'query_string' => [ 'query' => 'future' ]

]

];

$results = $client->search($params);

Page 14: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe 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”

Page 15: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe 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

Page 16: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe Weckx

16/22

Busca Composta

$params['body'] = [

'query' => [

'filtered' => [

'query' => [

'term' => [ 'titulo' => 'fut*' ]

],

'filter' => [

'match' => [ 'data' => '2014-12-05']

]

]

];

Page 17: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe 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

Page 18: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe 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' ]

]

]

];

Page 19: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe 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

},

]}

Page 20: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe 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

Page 21: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe Weckx

21/22

Perguntas?

Page 22: BigData - ElasticSearch + PHP

PHP Conference 2014 BigData – ElasticSearch + PHPFelipe Weckx

22/22

Obrigado!

Felipe [email protected]

@weckxgithub.com/weckx

linkedin.com/in/felipeweckxhttp://blog.weckx.net