如何:使用 PHP 在 Azure 搜索中进行分页搜索



我有这个PHP代码示例:

public function getListFromAzure($searchParam, $listCategory, $request){
$aListingManager = $this->get('recruitday.model_manager.job_listing');
$url = $jobListingManager->getAzureSearchParam($request, 'azure_search_idx');
$apiKey = $jobListingManager->getAzureSearchParam($request, 'azure_key');

$searchParam = preg_replace('/s+/', '+', $searchParam);
$postdata = json_encode(
array(
'search' => $searchParam,
'filter' => $listCategory,
'orderby'=> 'publishedDate desc',
'facets' => array('locationName','empType', 'workSchedule','listFunction','positionLevel','industry'),
'top' => 15,
)
);    

$opts = array(
'http'=>array(
'method'=>"POST",
'header'=>"Content-type: application/jsonrn" .
"api-key: ". $apiKey . "rn" .
"Accept: application/json",
'content'=>$postdata
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents($url, false, $context);
$file = json_decode($file,true);
return $file;
}

这在单个查询/页面上工作正常。 假设我要提取 10,000 条记录,并且在单个查询中,Azure 搜索的限制为 1000 条记录。 这应该提供 Azure 搜索参数$top - 其中指定要批量返回的项目数,$skip指定要跳过的项目数。 插入到这部分代码中:

$postdata = json_encode(
array(
'search' => $searchParam,
'filter' => $jobCategory,
'orderby'=> 'publishedDate desc',
'facets' => array('locationName','employmentType', 'workSchedule','jobFunction','positionLevel','industry'),
'top' => 15,
'skip' => 0,
'count' => true
)
);

假设此查询将针对要显示的前 =15 条记录的第一批/页。 对于下一个批次/页面,跳过将迭代例如为"跳过"=> 15。

问题是我不知道如何迭代这个参数。 还是我应该迭代这个? 还是有另一种方法? Azure 搜索参数参考:https://learn.microsoft.com/en-us/azure/search/search-pagination-page-layout

我正在考虑附加 json 文件。 相关搜索: 将数据追加到 .带有 PHP 的 JSON 文件

以前,我显示了 1000 条记录。 但我需要调整,因为我的记录已经有 1000 多条记录。 在前端 - 我通过ajax调用它。然后形成 HTML。 然后我通过jquery/javascript调整分页,变成每页20条记录的块(例如(。

希望我不要混淆任何人。 提前谢谢你! 干杯!

顺便说一句:我正在使用PHP,Symfony 2。

理想情况下,您的前端不需要一次处理 10000 条记录,因为用户很难管理这么大的列表,并且检索这么多记录可能非常慢。如果可能的话,你也应该让前端直接分页,在这种情况下,"top"和"skip"将从你的前端传入,PHP 代码会使用这些参数发出 1 个 POST 请求。

但是,如果这是不可能的,则可以使用搜索API,而无需对第一个请求使用"skip"和"top",然后遵循nextPageParameters的链。然后将每个页面的值附加到 1 个数组中,并将其返回到前端。

// $file = file_get_contents($url, false, $context); // without "top" and "skip"
// $file = json_decode($file,true);
$values = array();
while (True)
{
// get values from current page
$values = array_merge($array, $file["value"]);
// stop if there are no more pages
if (!array_key_exists("@search.nextPageParameters", $file))
{
break;
}
// get next page 
$postdata = $file["@search.nextPageParameters"];
$opts = array(
'http'=>array(
'method'=>"POST",
'header'=>"Content-type: application/jsonrn" .
"api-key: ". $apiKey . "rn" .
"Accept: application/json",
'content'=>$postdata
)
);
$context = stream_context_create($opts);
$file = file_get_contents($url, false, $context);
$file = json_decode($file, true);
}
return $values;

最新更新