ElasticSearch PHP - 获取类型/索引中10个(最新)项的列表

时间:2014-09-22 14:46:55

标签: php elasticsearch

我有一个名为publications_items的索引,类型名为" publication"。

我想要添加10个最新的出版物。 (一些匹配所有原则)

我正在使用ElasticSearch PHP(http://www.elasticsearch.org/guide/en/elasticsearch/client/php-api/current/_quickstart.html

基本上我只是默认获取但我不知道如何在ElasticSearchPHP中执行此操作。

在sense.qbox.io中我做:

POST /publications_items/_search {    "query": {
      "match_all": {}    } }

并且工作正常

映射:

PUT /publications_items/ {    "mappings": {
      "publication": {
         "properties": {
            "title": {
               "type": "string"
            },
            "url": {
               "type": "string"
            },
            "description": {
               "type": "string"
            },
            "year": {
               "type": "integer"
            },
            "author": {
               "type": "string"
            }
         }
      }    } }

1 个答案:

答案 0 :(得分:4)

您需要to enable "_timestamp" mapping

PUT /test/doc/_mapping
{
  "_timestamp": {
    "enabled": "true",
    "store": "true"
  }
}

在搜索查询中,您需要to sort by it并检索first 10 documents

GET /test/_search
{
  "sort" : {
    "_timestamp" : { "order" : "desc" }
  },
  "from" : 0, "size" : 10
}

特别是在Elasticsearch PHP中:

  • 映射更改:
require 'vendor/autoload.php';

$client = new Elasticsearch\Client();
$params = array();

$params2 = [
         '_timestamp' => [
             'enabled' => 'true',
             'store' => 'true'
         ]
];
$params['index']='test';
$params['type']='doc';
$params['body']['doc']=$params2;
$client->indices()->putMapping($params);
  • 查询:
require 'vendor/autoload.php';

$client = new Elasticsearch\Client();

$json = '{
  "sort" : {
    "_timestamp" : { "order" : "desc" }
  },
  "from" : 0, "size" : 10
}';

$params['index'] = 'test';
$params['type']  = 'doc';
$params['body'] = $json;

$results = $client->search($params);
echo json_encode($results, JSON_PRETTY_PRINT);