简体   繁体   中英

laravel elasticsearch search and paginate result

I installed Elasticsearch in laravel and need to get more than 10 result and paginate them. I am not able to get what should be code in laravel to get the desired result. below is my Post request Code

Route::post('search', 'Api\ProductController@search');

Search Post request Code:

  public function search(Request $request){
      
      $searchresult =  Product::search($request->input('search'))->get();
      return $searchresult;
  
}

According toElasticquent (Elasticsearch for Eloquent Laravel Models), In order to get more than 10 results (which is the default in elasticsearch) you can use the Query Based Search function:

public static function searchByQuery($query = null, $aggregations = null, $sourceFields = null, $limit = null, $offset = null, $sort = null)

The $limit parameter is the one you are looking for (Number of records to return).

I am able to increase result from 10 to whatever i want in 'size' field. I am still stuck as to how I can paginate so user can scroll result in app and more results are shown similar to normal pagination

    $client = ClientBuilder::create()->build();

          $params = $client->search([  
          "index"=> "products",
          
          "type" => "App\\Models\\Product",
          
          'body' => [
            "size" => 100,
              'query'=> [
                  'match'=>[
                      'name' => $request->input('search'),                       
                  ]
              ]
          ]
        ]);

        $result = $params['hits']['hits'];
       return $result;

You can use the from and to as they suggest in the query to paginate. You have to move both the numbers for every page.

GET /_search
{
  "from": 5,
  "size": 20,
  "query": {
    "match": {
      "user.id": "kimchy"
    }
  }
}

By default, you cannot use from and size to page through more than 10,000 hits

See if this package helps - https://github.com/rtamizh/laravel-es ( promotion for my own library though:) ). Here you can either use scroll or from function to get what you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM