ITeye博客

Nutch中写crawlDB的过程

yanglingstu · 2010-03-23 20:40 · nutch学习 · 编程语言 · Markdown

在爬取网一个页面之后,会解析出一些<url, 保存url信息的CrawlDatum对象>,这些键值对基本上分为三类: (1) 刚爬取的页面的url,及其对应的CrawlDatum对象,这时其CrawlDatum对象保存的一般页面分析后的一些信息,如爬取时间,分值等; (2) 从刚爬取的页面中解析出来的outlinks, 及其对应的CrawlDatum对象, 这时其CrawlDatum对象保存的一般都是一些初始化的信息,其状态一般也为unfetched之类的; (3) 从crawlDB读出来的url, 及其对应的CrawlDatum对象,将其从crawlDB中读出的目的是为了和前两者进行对比,把最值得的CrawlDatum对象对象更新到crawlDB中(也可能最值得的CrawlDatum对象就是先前从crawlDB中读出的那个)。

通过对以上三者的比较过滤之后,就将最终的result更新到crawlDB中,

调用关系是 CrawlDB ->进行Map处理:CrawlDbFilter –>进行Reduce处理:CrawlDbReducer。 其中: CrawlDB: 其作用就是设置Map/Reduce任务,并启动之。 CrawlDbFilter: 其作用是进行Map处理,其实就是进行简单的url的过滤和规整化操作,使得url符合标准(为后面的reduce生成统一的key(url),不做这些操作,可能把一些本来是同一个url的url,因为大小写不同给判定成不同的key,这时它们就进入不了同一个reduce处理中)。(因为代码简单这里就不细述) CrawlDbReducer:其作用是进行Reduce处理(其reduce()函数是写crawlDB的重点所在),这里的操作就集中了前面所讲的三类<url, 保存url信息的CrawlDatum对象>键值对的比较过滤操作,并将最终的处理结果result其写入crawlDB。其代码解析介绍如下: public void reduce(Text key, Iterator values, OutputCollector<Text, CrawlDatum> output, Reporter reporter) throws IOException {

boolean fetchSet = false;
boolean oldSet = false; //表示old是否已经设置过,第一次时认为没有设置过,第一次设置之后则设置为true
byte signature = null;
linked.clear();

while (values.hasNext()) {
  CrawlDatum datum = (CrawlDatum)values.next();
  if (CrawlDatum.hasDbStatus(datum)) {//对以前的处理的结果进行替换和填充
    if (!oldSet) { //需要替换以前的
      old.set(datum);
      oldSet = true;
    } else {
      // always take the latest version
      if (old.getFetchTime() < datum.getFetchTime()) old.set(datum); //保持old为最新的, 为什么呢?
    }
    continue;
  }

  if (CrawlDatum.hasFetchStatus(datum)) {
    if (!fetchSet) {
      fetch.set(datum);
      fetchSet = true;
    } else {
      // always take the latest version
      if (fetch.getFetchTime() < datum.getFetchTime()) fetch.set(datum);
    }
    continue;
  }

  switch (datum.getStatus()) {                // collect other info
  case CrawlDatum.STATUS_LINKED:
    CrawlDatum link = new CrawlDatum();
    link.set(datum);
    linked.add(link);
    break;
  case CrawlDatum.STATUS_SIGNATURE:
    signature = datum.getSignature();
    break;
  default:
    LOG.warn("Unknown status, key: " + key + ", datum: " + datum);
  }
}

// if it doesn't already exist, skip it
if (!oldSet && !additionsAllowed) return;

// if there is no fetched datum, perhaps there is a link , fetch未进行过,则fetch用linked.get(0)代替
if (!fetchSet && linked.size() > 0) {
  fetch = linked.get(0);
  fetchSet = true;
}
 
// still no new data - record only unchanged old data, if exists, and return
//处理没有fetch的情况,在没有提示为爬取过状态的情况下,保存为待爬取状态DbStatus(也可能连待爬取状态都不是)
if (!fetchSet) { //表示还没有抓取该url对应的页面,所以要保存为待爬取状态的url,及保存为DbStatus
  if (oldSet) // at this point at least "old" should be present 如果
    output.collect(key, old);
  else  //如果该url也没有表现为待爬取状态,则打印一下,后面就直接返回了
    LOG.warn("Missing fetch and old value, signature=" + signature);
  return;
}

if (signature == null) signature = fetch.getSignature();
long prevModifiedTime = oldSet ? old.getModifiedTime() : 0L;
long prevFetchTime = oldSet ? old.getFetchTime() : 0L;

// initialize with the latest version, be it fetch or link
//处理fetch和old都存在的情况,原则是尽量使得url对应的CrawlDatum对象是当前本次整体爬取中的最新的,因为一次整体爬取可能会耗去很长时间
result.set(fetch);
if (oldSet) { //这个if语句的目的是比较fetch和old两个CrawlDatum对象的状态来决定最终应该使result保存为old还是fetch,result是最终保存到crawlDB中的。
  // copy metadata from old, if exists
  if (old.getMetaData().size() > 0) {
    result.putAllMetaData(old);
    // overlay with new, if any
    if (fetch.getMetaData().size() > 0)
      result.putAllMetaData(fetch);
  }
  // set the most recent valid value of modifiedTime     
  if (old.getModifiedTime() > 0 && fetch.getModifiedTime() == 0) {//问题:fetch.getModifiedTime() == 0是不是表示一次爬取都没有过?如果不是难道不会导致死循环吗?因为一个url可能会始终出出现为old.getModifiedTime() > 0。
    result.setModifiedTime(old.getModifiedTime());
  }
}

switch (fetch.getStatus()) {                // determine new status
case CrawlDatum.STATUS_LINKED:   // it was link  对前面的执行过 fetch = linked.get(0);代码的情况 进行处理
  if (oldSet) {                          // if old exists
    result.set(old);                          // use it
  } else {
    result = schedule.initializeSchedule((Text)key, result);
    result.setStatus(CrawlDatum.STATUS_DB_UNFETCHED);
    try {
      scfilters.initialScore((Text)key, result);//初始化url的分值
    } catch (ScoringFilterException e) {
      if (LOG.isWarnEnabled()) {
        LOG.warn("Cannot filter init score for url " + key +
                 ", using default: " + e.getMessage());
      }
      result.setScore(0.0f);
    }
  }
  break;
  
case CrawlDatum.STATUS_FETCH_SUCCESS:         // succesful fetch
case CrawlDatum.STATUS_FETCH_REDIR_TEMP:      // successful fetch, redirected
case CrawlDatum.STATUS_FETCH_REDIR_PERM:
case CrawlDatum.STATUS_FETCH_NOTMODIFIED:     // successful fetch, notmodified
  // determine the modification status
  int modified = FetchSchedule.STATUS_UNKNOWN;
  if (fetch.getStatus() == CrawlDatum.STATUS_FETCH_NOTMODIFIED) {
    modified = FetchSchedule.STATUS_NOTMODIFIED;
  } else {
    if (oldSet && old.getSignature() != null && signature != null) {
      if (SignatureComparator._compare(old.getSignature(), signature) != 0) {
        modified = FetchSchedule.STATUS_MODIFIED;
      } else {
        modified = FetchSchedule.STATUS_NOTMODIFIED;
      }
    }
  }
  // set the schedule
  result = schedule.setFetchSchedule((Text)key, result, prevFetchTime,
      prevModifiedTime, fetch.getFetchTime(), fetch.getModifiedTime(), modified);
  // set the result status and signature
  if (modified == FetchSchedule.STATUS_NOTMODIFIED) {
    result.setStatus(CrawlDatum.STATUS_DB_NOTMODIFIED);
    if (oldSet) result.setSignature(old.getSignature());
  } else {
    switch (fetch.getStatus()) {
    case CrawlDatum.STATUS_FETCH_SUCCESS:
      result.setStatus(CrawlDatum.STATUS_DB_FETCHED);
      break;
    case CrawlDatum.STATUS_FETCH_REDIR_PERM:
      result.setStatus(CrawlDatum.STATUS_DB_REDIR_PERM);
      break;
    case CrawlDatum.STATUS_FETCH_REDIR_TEMP:
      result.setStatus(CrawlDatum.STATUS_DB_REDIR_TEMP);
      break;
    default:
      LOG.warn("Unexpected status: " + fetch.getStatus() + " resetting to old status.");
      if (oldSet) result.setStatus(old.getStatus());
      else result.setStatus(CrawlDatum.STATUS_DB_UNFETCHED);
    }
    result.setSignature(signature);
  }
  // if fetchInterval is larger than the system-wide maximum, trigger
  // an unconditional recrawl. This prevents the page to be stuck at
  // NOTMODIFIED state, when the old fetched copy was already removed with
  // old segments.
  if (maxInterval < result.getFetchInterval())
    result = schedule.forceRefetch((Text)key, result, false);
  break;
case CrawlDatum.STATUS_SIGNATURE:
  if (LOG.isWarnEnabled()) {
    LOG.warn("Lone CrawlDatum.STATUS_SIGNATURE: " + key);
  }   
  return;
case CrawlDatum.STATUS_FETCH_RETRY:           // temporary failure
  if (oldSet) {
    result.setSignature(old.getSignature());  // use old signature
  }
  result = schedule.setPageRetrySchedule((Text)key, result, prevFetchTime,
      prevModifiedTime, fetch.getFetchTime());
  if (result.getRetriesSinceFetch() < retryMax) {
    result.setStatus(CrawlDatum.STATUS_DB_UNFETCHED);
  } else {
    result.setStatus(CrawlDatum.STATUS_DB_GONE);
  }
  break;

case CrawlDatum.STATUS_FETCH_GONE:            // permanent failure
  if (oldSet)
    result.setSignature(old.getSignature());  // use old signature
  result.setStatus(CrawlDatum.STATUS_DB_GONE);
  result = schedule.setPageGoneSchedule((Text)key, result, prevFetchTime,
      prevModifiedTime, fetch.getFetchTime());
  break;

default:
  throw new RuntimeException("Unknown status: " + fetch.getStatus() + " " + key);
}

try {
  scfilters.updateDbScore((Text)key, oldSet ? old : null, result, linked);
} catch (Exception e) {
  if (LOG.isWarnEnabled()) {
    LOG.warn("Couldn't update score, key=" + key + ": " + e);
  }
}
// remove generation time, if any
result.getMetaData().remove(Nutch.WRITABLE_GENERATE_TIME_KEY);
output.collect(key, result);

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。