Paul
Paul

Reputation: 858

ElasticSearch PHP - get list of 10 (most recent) items in type/index

I have a index called publications_items and type called "publication".

I'd like to have the 10 most recent added publications. (some matchAll principle)

I'm using ElasticSearch PHP (http://www.elasticsearch.org/guide/en/elasticsearch/client/php-api/current/_quickstart.html)

Basically i'm just doing a default get but i would not know how to do this in ElasticSearchPHP.

In sense.qbox.io i do :

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

and it works fine

mapping:

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

Upvotes: 2

Views: 2725

Answers (1)

Andrei Stefan
Andrei Stefan

Reputation: 52368

You need to enable "_timestamp" mapping:

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

And in your search query you need to sort by it and retrieve the first 10 documents:

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

And specifically in Elasticsearch PHP:

  • mappings change:
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);
  • query:
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);

Upvotes: 4

Related Questions