2014-09-26 102 views
1

我有一個基於URL的索引http://example.com/sitemap.index.xml其中index是一個數字>0定義什麼結果應包括在每個塊生成網站地圖的腳本。Elasticsearch滾動API搜索「從」

$chunk = 10000; 
$counter = 0; 

$scroll = $es->search(array(
    "index" => "index", 
    "type" => "type", 
    "scroll" => "1m", 
    "search_type" => "scan", 
    "size" => 10, 
    "from" => $chunk * ($index - 1) 
)); 
$sid = $scroll['_scroll_id']; 

while($counter < $chunk){ 
    $docs = $es->scroll(array(
     "scroll_id" => $sid, 
     "scroll" => "1m" 
    )); 
    $sid = $docs['_scroll_id']; 
    $counter += count($docs['hits']['hits']); 
} 

// ... 

現在我每次訪問http://example.com/sitemap.1.xmlhttp://example.com/sitemap.2.xml從ES返回的結果是完全一樣的。它返回50結果(每個碎片10個),但似乎不需要計數from = 0,from = 10000

我使用elasticsearch-php作爲ES庫。

任何想法?

+0

你的意思是說,對於每一次迭代,重做的結果是一樣的嗎? – Shastry 2014-09-26 12:15:34

+0

@Shastry,是的,無論'from =?'傳遞給最初的'search()'請求,結果都是一樣的。 – 2014-09-26 12:19:12

+0

我已經在Java中使用了掃描和滾動。但我沒有進入這種情況。我可以爲你提供Java代碼嗎? – Shastry 2014-09-26 12:27:33

回答

0

在Java中,可進行如下

QueryBuilder query = QueryBuilders.matchAllQuery(); 
SearchResponse scrollResp = Constants.client.prepareSearch(index) 
     .setTypes(type).setSearchType(SearchType.SCAN) 
     .setScroll(new TimeValue(600000)).setQuery(query) 
     .setSize(500).execute().actionGet(); 
while (true) { 
    scrollResp = Constants.client 
      .prepareSearchScroll(scrollResp.getScrollId()) 
      .setScroll(new TimeValue(600000)).execute().actionGet(); 
    System.out.println("Record count :" 
      + scrollResp.getHits().getHits().length); 
    total = total + scrollResp.getHits().getHits().length; 
    System.out.println("Total record count: " + total); 
    for (SearchHit hit : scrollResp.getHits()) { 
    //handle the hit 
    } 
    // Break condition: No hits are returned 
    if (scrollResp.getHits().getHits().length == 0) { 
     System.out.println("All records are fetched"); 
     break; 
    } 
} 

希望它能幫助來完成。

+0

謝謝你的回覆,但我沒有請參閱搜索查詢中的'setFrom(?)'。你的例子適用於返回特定'_type'的所有記錄,但不是來自它的特定塊。正如我原來的問題所說,我正在構建一個站點地圖,所以我偏離了文檔大小和URL數量的限制,因此我需要將所有站點地圖分割爲更小的站點地圖'sitemap.1.xml','sitemap.2。 xml'。因此,每個對「url/sitemap.1.xml」的請求都將返回第一個「10000」匹配,對於「url/sitemap.2.xml」,它會返回匹配在「10001」和「20000」之間的匹配。 – 2014-09-26 12:52:53