2012-11-08 29 views
4

这是使用弹性曲线和查询数据从ElasticSearch如何查询使用弹性曲线

对我来说,我的第一次出任首发我对如何查询下面使用弹性曲线?:

curl 'http://localhost:9200/myindex/_search?pretty=true' -d '{  
    "query" : { 
    "term": { 
     "click": "true" 
    } }, "facets" : { 
    "matches" : { 
     "terms" : { 
      "field" : "pubid", 
      "all_terms" : true, 
      "size": 200 
     } 
    } 
    } 
}' 
代码中的问题

希望有人可以在这里借给我一只手臂。

感谢,

回答

8

这应该这样做:

// Create a "global" query 
$query = new Elastica_Query; 

// Create the term query 
$term = new Elastica_Query_Term; 
$term->setTerm('click', 'true'); 

// Add term query to "global" query 
$query->setQuery($term); 

// Create the facet 
$facet = new Elastica_Facet_Terms('matches'); 
$facet->setField('pubid') 
     ->setAllTerms(true) 
     ->setSize(200); 

// Add facet to "global" query 
$query->addFacet($facet); 

// Output query 
echo json_encode($query->toArray()); 

要运行查询,则需要conntect你ES服务器

// Connect to your ES servers 
$client = new Elastica_Client(array(
    'servers' => array(
     array('host' => 'localhost', 'port' => 9200), 
     array('host' => 'localhost', 'port' => 9201), 
     array('host' => 'localhost', 'port' => 9202), 
     array('host' => 'localhost', 'port' => 9203), 
     array('host' => 'localhost', 'port' => 9204), 
    ), 
)); 

,并指定索引,然后键入您希望对您的查询运行

// Get index 
$index = $client->getIndex('myindex'); 
$type = $index->getType('typename'); 

现在可以运行你的查询

$type->search($query); 

编辑: 如果您正在使用一个命名空间环境和当前版本的弹性曲线的,改变其中新对象相应地创建

的所有行
$query = new \Elastica\Query; 
$facet = new \Elastica\Facet\Terms 

+0

这是一个很好的答案。 – webblover

1

您还可以查询这样的: (感谢http://tech.vg.no/2012/07/03/using-elastica-to-query-elasticsearch/的优秀文章)

<?php 
$query = new Elastica_Query_Builder('{  
    "query" : { 
     "term": { 
      "click": "true" 
      } 
     }, 
    "facets" : { 
     "matches" : { 
      "terms" : { 
       "field" : "pubid", 
       "all_terms" : true, 
       "size": 200 
       } 
      } 
     } 
    }'); 

// Create a raw query since the query above can't be passed directly to the search method used below 
$query = new Elastica_Query($query->toArray()); 

// Create the search object and inject the client 
$search = new Elastica_Search(new Elastica_Client()); 

// Configure and execute the search 
$resultSet = $search->addIndex('blog') 
        ->addType('posts') 
        ->search($query); 

// Loop through the results 
foreach ($resultSet as $hit) { 
    // ... 
}