首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Elastica进行查询

如何使用Elastica进行查询
EN

Stack Overflow用户
提问于 2012-11-08 16:33:03
回答 2查看 9.4K关注 0票数 4

这是我第一次使用Elastica并从ElasticSearch查询数据

对于我来说,作为初学者,我有一个关于如何使用Elastica查询以下代码的问题:

代码语言:javascript
复制
curl 'http://localhost:9200/myindex/_search?pretty=true' -d '{     
  "query" : {
    "term": {
      "click": "true"
    }   },   "facets" : {
    "matches" : {
      "terms" : {
          "field" : "pubid",
          "all_terms" : true,
          "size": 200 
      }
    }   
  } 
}'

希望有人能帮我一把。

谢谢,

EN

回答 2

Stack Overflow用户

发布于 2012-11-13 22:55:22

这应该可以做到:

代码语言:javascript
复制
// 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());

要运行查询,您需要连接到ES服务器

代码语言:javascript
复制
// 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),
    ),
));

并指定要对其运行查询的索引和类型

代码语言:javascript
复制
// Get index
$index = $client->getIndex('myindex');
$type = $index->getType('typename');

现在,您可以运行查询了

代码语言:javascript
复制
$type->search($query);

编辑:如果您使用的是命名空间环境和当前版本的Elastica,请相应地将创建新对象的所有行更改为

代码语言:javascript
复制
$query = new \Elastica\Query;
$facet = new \Elastica\Facet\Terms

诸若此类

票数 8
EN

Stack Overflow用户

发布于 2015-01-13 11:26:36

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

代码语言:javascript
复制
<?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) {
    // ...
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13285250

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档