免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4440 | 回复: 1
打印 上一主题 下一主题

医疗相关信息的抓取 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-07-22 17:12 |只看该作者 |倒序浏览
这完完全全是我自己一个人写的,整个都写在一个类啊,对获取最新的页面的方式使用的hash对比,这个有时候准确,有时候就不行。一般情况效率还是很好的.

代码:
  1. package com.huntto.nbinf.dao.impl;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.lang.ref.SoftReference;
  5. import java.net.MalformedURLException;
  6. import java.rmi.Naming;
  7. import java.rmi.RemoteException;
  8. import java.rmi.registry.LocateRegistry;
  9. import java.rmi.server.UnicastRemoteObject;
  10. import java.security.MessageDigest;
  11. import java.security.NoSuchAlgorithmException;
  12. import java.text.SimpleDateFormat;
  13. import java.util.ArrayList;
  14. import java.util.Calendar;
  15. import java.util.Date;
  16. import java.util.HashMap;
  17. import java.util.Iterator;
  18. import java.util.List;
  19. import java.util.Map;
  20. import java.util.Properties;
  21. import java.util.Stack;
  22. import java.util.regex.Matcher;
  23. import java.util.regex.Pattern;
  24. import net.paoding.analysis.analyzer.PaodingAnalyzer;
  25. import org.apache.log4j.Logger;
  26. import org.apache.lucene.analysis.Analyzer;
  27. import org.apache.lucene.document.Document;
  28. import org.apache.lucene.document.Field;
  29. import org.apache.lucene.document.Field.Index;
  30. import org.apache.lucene.document.Field.Store;
  31. import org.apache.lucene.index.IndexWriter;
  32. import org.apache.lucene.index.IndexWriter.MaxFieldLength;
  33. import org.apache.lucene.index.Term;
  34. import org.apache.lucene.queryParser.ParseException;
  35. import org.apache.lucene.queryParser.QueryParser;
  36. import org.apache.lucene.search.BooleanClause.Occur;
  37. import org.apache.lucene.search.BooleanQuery;
  38. import org.apache.lucene.search.Filter;
  39. import org.apache.lucene.search.FuzzyQuery;
  40. import org.apache.lucene.search.IndexSearcher;
  41. import org.apache.lucene.search.RangeFilter;
  42. import org.apache.lucene.search.RangeQuery;
  43. import org.apache.lucene.search.ScoreDoc;
  44. import org.apache.lucene.search.Sort;
  45. import org.apache.lucene.search.SortField;
  46. import org.apache.lucene.search.TermQuery;
  47. import org.apache.lucene.search.TopDocs;
  48. import org.apache.lucene.search.TopFieldDocs;
  49. import org.apache.lucene.store.FSDirectory;
  50. import org.jsoup.Connection;
  51. import org.jsoup.helper.HttpConnection;
  52. import org.jsoup.nodes.Element;
  53. import org.jsoup.select.Elements;
  54. import com.huntto.nbinf.dao.IForQtSearch;
  55. import com.huntto.nbinf.dao.IListInfoDAO;
  56. import com.huntto.nbinf.pojo.LucenePage;


  57. public class LucenService extends UnicastRemoteObject implements IForQtSearch {
  58.      
  59.      
  60.     File filestack,fileindex;
  61.     //当前URLS
  62.     Stack<String> stackcurt=new Stack<String>();
  63.     //下一层URLS
  64.     Stack<String> stacknext=new Stack<String>();
  65.      
  66.     Logger logger=Logger.getLogger("lucene");
  67.     //设置深度
  68.     final int deep;

  69.     //当前深度
  70.     private int curtdeep=1;
  71.      
  72.     //查询的最大结果数
  73.     final int maxresult=1024;
  74.      
  75.     //关键字是标题命中
  76.     final int pagetype_title=1;
  77.      
  78.     //关键字是meta命中
  79.     final int pagetype_meta=2;
  80.      
  81.     //关键字是body命中
  82.     final int pagetype_body=3;
  83.      
  84.     //超过这个数就写到文件
  85.     final int max_to_writefile=10;
  86.      
  87.     //方便处理日期
  88.     final SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
  89.      
  90.     //庖丁分词器
  91.     private Analyzer analyzer=new PaodingAnalyzer();
  92.      
  93.     //dui
  94.     private LuceneStackControll controll=new LuceneStackControll();
  95.      
  96.     //文件控制类,文件中存放的是需要处理的url队列,由于队列的长度可能会很大,因此存放在文件中
  97.     private FileControll fileControll=new FileControll();
  98.      
  99.     //lucene 文件操作
  100.     private FSDirectory directory;
  101.      

  102.     //lucene 更新索引文件
  103.     IndexWriter indexWriter;
  104.      
  105.     Date yesday,today;
  106.     //rs 关键字分组,
  107.     String urls[],websites[][],rs[][];
  108.      
  109.     SoftReference<String[][]> softReference=new SoftReference<String[][]>(websites);
  110.     final String userAgent="Mozilla/5.0 (Windows NT 6.1; WOW64) "
  111.             + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.101 Safari/537.36";
  112.      
  113.     protected IListInfoDAO halleyCurrencyDao;
  114.      
  115.     public LucenService() throws RemoteException{
  116.          
  117.         Properties properties=new Properties();
  118.         int prodeep=5;
  119.         int luceneport=8999;
  120.         String lucenename="lucenesearchs";
  121.         File dirc=null;
  122.          
  123.         try {
  124.             properties.load(LucenService.class.getClassLoader().
  125.                     getResourceAsStream("paoding-dic-names.properties"));
  126.             dirc=new File(properties.getProperty("dirc"));         
  127.             directory=FSDirectory.getDirectory(dirc);
  128.             IndexWriter.unlock(directory);
  129.             indexWriter=new IndexWriter(directory,analyzer,MaxFieldLength.UNLIMITED);
  130.             
  131.             prodeep=Integer.parseInt(properties.getProperty("deep"));
  132.             luceneport=Integer.parseInt(properties.getProperty("luceneport"));
  133.             lucenename=properties.getProperty("lucenename");
  134.         } catch (IOException e1) {
  135.             e1.printStackTrace();
  136.         }
  137.          
  138.         deep=prodeep;
  139.          
  140.         if(dirc==null)
  141.             dirc=new File("c:/dirc");
  142.             LocateRegistry.createRegistry(8999);
  143.             try {
  144.                 Naming.rebind("rmi://localhost:"+luceneport+"/"+lucenename+"", this);
  145.             } catch (MalformedURLException e) {
  146.                 e.printStackTrace();
  147.             }
  148.          
  149.     }
  150.      
  151.     /**
  152.      * 开始工作
  153.      */
  154.     public void wok(){

  155.          
  156.         logger.debug("开始工作");
  157.          
  158.         if(websites==null||websites.length==0){
  159.             try {
  160.                 //只从指定的网站开始抓取
  161.                 websites=halleyCurrencyDao.opensExcuteSQL("select MONITORURL from CONSENSUSINTERNET where rownum<10");
  162.             } catch (IOException e) {
  163.                 e.printStackTrace();
  164.             }
  165.         }
  166.     urls=new String[10];
  167.         int j=0;
  168.         if(websites!=null){
  169.             for(int i=0;i<websites.length;i++){
  170.                 if(i%10==0&&i!=0){
  171.                   j=0;  
  172.                   startWork(urls);
  173.                 }
  174.                 urls[j++]=websites[i][0];
  175.             }
  176.             
  177.             if(j!=0){
  178.                 startWork(urls);
  179.             }
  180.         }
  181.             
  182.          
  183.     }
  184.     private void initdate(){
  185.         Calendar calendar=Calendar.getInstance();
  186.         calendar.add(Calendar.DATE,-1);
  187.         yesday=calendar.getTime();
  188.         today=new Date();
  189.     }
  190.      
  191.     /**
  192.      * 开始工作
  193.      * 对urls都放在stackcurts里面,
  194.      * 如果stackcurt为空就会从文件或者stacknext里面读取url赋值到stackcurt,
  195.      * 如果从文件或stackcurt都不能获得,就应该结束循环
  196.      *
  197.      * @param urls 需要处理的urls
  198.      */
  199.     public void startWork(String...urls){

  200.         curtdeep=1;
  201.         initdate();
  202.         for (int i = 0; i < urls.length; i++)
  203.             stackcurt.push(urls[i]);
  204.          
  205.         controll.fin=false;
  206.         while(true)
  207.            {
  208.             if(stackcurt.isEmpty()){
  209.                 if(controll.fin
  210.                         &&controll.sygs<=0
  211.                         &&controll.curtindex>0){
  212.                     controll.fin=false;
  213.                     if(controll.indata[0].delete())
  214.                         controll.indata[1].delete();
  215.                 }
  216.                 getCurtStack();
  217.             }
  218.             if(stackcurt.isEmpty())  break;
  219.             try {
  220.                 pageContent(stackcurt.pop(),false);
  221.             } catch (Exception e) {
  222.                 e.printStackTrace();
  223.             }
  224.            }
  225.         curtdeep=1;
  226.     }
  227.     /**
  228.      * 得到页面内容
  229.      * @param url
  230.      * @param deeporshenheindex 参数指示是否分析页面内的链接和页面审核状态
  231.      * 强制索引不管是不是刚刚索引过
  232.      * @throws IOException
  233.      */
  234.     public void pageContent(String url,boolean shenhe) throws IOException{
  235.      
  236.         Connection connection=HttpConnection.connect(url);
  237.         connection.ignoreContentType(true);
  238.         connection.ignoreHttpErrors(true);
  239.         connection.userAgent(userAgent);
  240.          
  241.         org.jsoup.nodes.Document document= connection.get();
  242.         IndexInfo indexInfo=new IndexInfo();
  243.             
  244.         Elements elements=document.getElementsByTag("meta");
  245.         indexInfo.string=document.title();
  246.         indexInfo.type=pagetype_title;
  247.         fenZhu(indexInfo);
  248.          
  249.          
  250.         Iterator<Element> iterator=elements.iterator();
  251.         indexInfo.type=pagetype_meta;
  252.         while(iterator.hasNext()){
  253.               Element element=iterator.next();
  254.               if("Keywords".equalsIgnoreCase(element.attr("name"))
  255.                     ||"Description".equalsIgnoreCase(element.attr("name"))){
  256.                   indexInfo.string=element.attr("content");
  257.                   fenZhu(indexInfo);
  258.               }
  259.         }
  260.          
  261.         elements=document.getElementsByTag("body");
  262.         if(elements.size()>0)
  263.         {
  264.             indexInfo.type=pagetype_body;
  265.             indexInfo.string=elements.get(0).text();
  266.             fenZhu(indexInfo);
  267.         }
  268.         indexInfo.url=url;
  269.         if(indexInfo.group_keyword!=null){
  270.             indexInfo.store=true;
  271.             indexInfo.group=indexInfo.group_keyword[1];
  272.             indexInfo.keyword=indexInfo.group_keyword[0];
  273.             indexInfo.string=document.text();
  274.             indexInfo.shenhe=shenhe;
  275.             indexInfo.title=document.title();
  276.         }else
  277.             indexInfo.store=false;
  278.          
  279.          if(isUpdatePage(md5(indexInfo.url), md5(indexInfo.string))||shenhe)
  280.              indexPageContent(indexInfo);
  281.                  
  282.         if(curtdeep<this.deep){
  283.              elements=document.getElementsByTag("a");
  284.              iterator=elements.iterator();
  285.             while(iterator.hasNext()){
  286.                 Element element=iterator.next();
  287.                 String attrurl=element.attr("href");
  288.                 attrurl=processUrl(attrurl, url);
  289.                 try {
  290.                     if((!isIndexed(attrurl))&&
  291.                             linkXg(element))
  292.                     if(!stacknext.contains(attrurl))
  293.                     {
  294.                         stacknext.push(attrurl);
  295.                         System.out.println(attrurl+"添加到队列");
  296.                         if(stacknext.size()>max_to_writefile)
  297.                             controll.filecount+=writeToFile();
  298.                     }
  299.                      
  300.                 } catch (IOException e) {
  301.                     e.printStackTrace();
  302.                 }   
  303.             }
  304.         }

  305.     }
  306.      
  307.     /**
  308.      * 判断这个链接是不是先关
  309.      * @param link
  310.      * @return
  311.      */
  312.     public boolean linkXg(Element link){
  313.         if( !constainsKeyWord(link.text())){
  314.             link=link.parent();
  315.             if(link.tagName().equalsIgnoreCase("body"))
  316.                 return false;
  317.             if( !constainsKeyWord(link.text()))
  318.               return false;
  319.         }      
  320.         return true;
  321.     }
  322.      
  323.     /**
  324.      * 获取url
  325.      */
  326.       private void getCurtStack(){
  327.             
  328.            //这是新一层的开始
  329.            if(!controll.fin)
  330.            {
  331.                logger.debug("从stacknext获得url");
  332.                curtdeep++;
  333.                stackcurt=stacknext;
  334.                stacknext=new Stack<String>();   
  335.                if(controll.filecount>max_to_writefile)
  336.                {
  337.                    controll.fin=true;
  338.                    controll.swapInOut();
  339.                }
  340.            }
  341.           else
  342.           {
  343.               logger.debug("从文件"+controll.indata[0].getName()+"获得url");
  344.                stackcurt=readStackFile(controll.curtindex,max_to_writefile);
  345.                controll.curtindex+=stackcurt.size();
  346.           }
  347.        }
  348.          
  349.          
  350.         /**
  351.          *
  352.          *  把next写到文件
  353.          *
  354.          * @return 写入的个数
  355.          */
  356.         private int writeToFile(){
  357.             int count=0;
  358.             try {
  359.                 count=fileControll.writeStringArr(stacknext.toArray(new String[]{}),
  360.                         controll.outdata[0],
  361.                         controll.outdata[1]);
  362.                  
  363.                  logger.debug("将多余的url写入到文件"+controll.outdata[0].getName());
  364.             } catch (IOException e) {
  365.                 e.printStackTrace();
  366.             }
  367.             if(count>0)
  368.                 stacknext=new Stack<String>();
  369.             
  370.             return count;
  371.         }
  372.         /**
  373.          * 读取
  374.          * @param n
  375.          * @param total
  376.          * @return
  377.          */
  378.         public Stack<String> readStackFile(int n,int total){
  379.             String[] strings=null;
  380.             Stack<String> stack=null;
  381.              try {
  382.                  strings=fileControll.readStringArr(
  383.                          controll,
  384.                          n, total);
  385.             } catch (IOException e) {
  386.                 e.printStackTrace();
  387.             }
  388.              if(strings!=null){
  389.                  stack=new Stack<String>();
  390.                 for(int i=0;i<strings.length;i++){
  391.                     stack.push(strings[i]);
  392.                 }
  393.              }
  394.             return stack;
  395.         }
  396.     /**
  397.      *  获得页面内容
  398.      * @param string
  399.      * @param url
  400.      * @param title
  401.      * @throws IOException
  402.      */
  403.     private void indexPageContent(IndexInfo indexInfo) throws IOException{  
  404.          
  405.            Document document=new Document();
  406.         document.add(new Field("url",indexInfo.url,Store.YES,Index.ANALYZED));
  407.         document.add(new Field("md5code", md5(indexInfo.url),Store.YES,Index.ANALYZED));        
  408.         document.add(new Field("id", md5(indexInfo.url)+System.currentTimeMillis(),Store.YES,Index.ANALYZED));

  409.         if(indexInfo.store){
  410.             
  411.             if(today==null)
  412.                 initdate();
  413.             
  414.             System.out.println("存储"+indexInfo.url+"关键字:"+indexInfo.keyword+"\t"+indexInfo.title);
  415.             
  416.             logger.debug("存储url"+indexInfo.url);
  417.             document.add(new Field("title", indexInfo.title,Store.YES,Index.ANALYZED));
  418.             document.add(new Field("store", "t",Store.YES,Index.ANALYZED));
  419.             document.add(new Field("content",indexInfo.string,Store.NO,Index.ANALYZED));
  420.             document.add(new Field("shenhe",indexInfo.shenhe?"1":"0",Store.YES,Index.ANALYZED));
  421.             document.add(new Field("group", indexInfo.group, Store.YES,Index.ANALYZED));
  422.             document.add(new Field("keyword", indexInfo.keyword, Store.YES,Index.ANALYZED));
  423.             document.add(new Field("score", ""+indexInfo.score, Store.YES,Index.ANALYZED));
  424.             document.add(new Field("ctime",today.getTime()+"" ,Store.YES,Index.ANALYZED));
  425.             document.add(new Field("md5contentcode", md5(indexInfo.string),Store.YES,Index.ANALYZED));
  426.             
  427.             
  428.         }else
  429.             document.add(new Field("store", "f",Store.YES,Index.ANALYZED));
  430.      
  431.         indexWriter.updateDocument(new Term("md5code", md5(indexInfo.url)),document);
  432.         indexWriter.commit();
  433.         indexWriter.optimize();

  434.     }
  435.     /**
  436.      * 关键字分组
  437.      * @param content
  438.      * @return
  439.      * @throws IOException
  440.      */
  441.     private void fenZhu(IndexInfo indexInfo) throws IOException{
  442.         indexInfo.string=indexInfo.string.replace("\\s", "");
  443.         if(rs==null)
  444.             //根据页面的信息判断是不是应该
  445.             rs= halleyCurrencyDao.opensExcuteSQL("select t2.keyword,t3.keyword from CONSENSUSTEAM_KEY t1 LEFT JOIN  CONSENSUSKEYWORD t2 on t1.keyid=T2.id left join CONSENSUSKEYWORDTEAM t3 on t1.teamid=t3.teamid");   
  446.         StringBuilder keyword=null;
  447.         StringBuilder keywordtype=null;
  448.         for(int i=0;i<rs.length;i++){
  449.             if(indexInfo.string.contains(rs[i][0]))
  450.             {
  451.                 switch(indexInfo.type){
  452.                     case pagetype_title:
  453.                         indexInfo.score+=10;
  454.                     break;
  455.                     case pagetype_meta:
  456.                         indexInfo.score+=5;
  457.                         break;
  458.                     case pagetype_body:
  459.                         indexInfo.score+=1;
  460.                         break;
  461.                 }

  462.                 if(indexInfo.group_keyword==null)
  463.                     indexInfo.group_keyword=new String[2];
  464.                 else if(indexInfo.group_keyword[0]!=null){
  465.                         if(indexInfo.group_keyword[0].contains(rs[i][0]))
  466.                             continue;
  467.                         if(indexInfo.group_keyword[1].contains(rs[i][1]))
  468.                             continue;
  469.                 }
  470.                  
  471.                 if(keyword==null){
  472.                     keyword=new StringBuilder();
  473.                     keywordtype=new StringBuilder();
  474.                 }
  475.                 if(keyword.indexOf(rs[i][0])<0)
  476.                     keyword.append("#"+rs[i][0]);
  477.                 if(keywordtype.indexOf(rs[i][1])<0)
  478.                     keywordtype.append("#"+rs[i][1]);
  479.             }
  480.         }
  481.          
  482.         if(keyword!=null)
  483.         {
  484.             indexInfo.group_keyword[0]=(indexInfo.group_keyword[0]==null?
  485.                     "":indexInfo.group_keyword[0])+keyword.toString();
  486.             indexInfo.group_keyword[1]=(
  487.                     indexInfo.group_keyword[1]==null?"":indexInfo.group_keyword[1]
  488.                     )+keywordtype.toString();
  489.         }

  490.     }
  491.     /**
  492.      * 查看这个链接是否包含关键字
  493.      * @param content
  494.      * @return
  495.      */
  496.     private boolean constainsKeyWord(String content){
  497.         content=content.replace("\\s", "");
  498.         if(rs==null)
  499.             try {
  500.                 rs= halleyCurrencyDao.opensExcuteSQL("select t2.keyword,t3.keyword from CONSENSUSTEAM_KEY t1 LEFT JOIN  CONSENSUSKEYWORD t2 on t1.keyid=T2.id left join CONSENSUSKEYWORDTEAM t3 on t1.teamid=t3.teamid");
  501.             } catch (IOException e) {
  502.                 e.printStackTrace();
  503.             }
  504.          for(int i=0;i<rs.length;i++){
  505.             if(content.contains(rs[i][0]))
  506.              return true;   
  507.         }
  508.         return false;
  509.     }
  510.      
  511.     /**
  512.      * 审核URL
  513.      * @param url
  514.      * @throws IOException
  515.      */
  516.     public void shenHe(String url) throws IOException{
  517.          
  518.         logger.debug("审核"+url);
  519.         pageContent(url,true);
  520.     }
  521.     /**
  522.      * 根据ID审核
  523.      * @param id
  524.      * @throws IOException
  525.      */
  526.     public void shenHeById(String id) throws IOException{
  527.          
  528.         IndexSearcher indexSearcher=new IndexSearcher(directory);
  529.         TermQuery query=new TermQuery(new Term("id", id));
  530.          
  531.         TopDocs docs= indexSearcher.search(query, 1);

  532.         Document document2=null;
  533.         ScoreDoc[] docss=docs.scoreDocs;
  534.          if(docs!=null&&docss.length>0){
  535.              for (int i = 0; i < docss.length; i++) {
  536.                  document2=indexSearcher.doc(docss[i].doc);
  537.             }
  538.          }
  539.          if(document2!=null){
  540.              shenHe(document2.getField("url").stringValue());
  541.               
  542.          }
  543.   
  544.     }
  545.      
  546.     /**
  547.      * 查询 url是否已经被索引了
  548.      * 只能保证一天内的链接不被重复索引
  549.      * @param url
  550.      * @return
  551.      * @throws IOException
  552.      */
  553.     private boolean isIndexed(String url) throws IOException{
  554.          
  555.          
  556.         if(!directory.fileExists("segments.gen"))
  557.             return false;

  558.         IndexSearcher indexSearcher=new IndexSearcher(directory);
  559.         TermQuery query=new TermQuery(new Term("md5code", md5(url)));
  560.         BooleanQuery booleanQuery=new BooleanQuery();
  561.         booleanQuery.add(query,Occur.MUST);
  562.         booleanQuery.add(
  563.                 new RangeQuery(
  564.                 new Term("ctime",yesday.getTime()+""),
  565.                 new Term("ctime",today.getTime()+""),
  566.                 true),
  567.                 Occur.MUST );
  568.         //保证相同的链接一天只能抓取一次
  569.         TopDocs docs= indexSearcher.search(booleanQuery, 1);
  570.         indexSearcher.close();
  571.          
  572.         if(docs.scoreDocs.length>0){
  573.             logger.debug("已结被索引了"+url);
  574.         }
  575.          
  576.         return docs.scoreDocs.length>0?true:false;
  577.     }
  578.      
  579.     /**
  580.      * 判断页面是不是最新的
  581.      * @param md5code
  582.      * @param contentMD5
  583.      * @return
  584.      * @throws IOException
  585.      */
  586.     private boolean isUpdatePage(String md5code,String contentMD5) throws  IOException{
  587.          
  588.         if(!directory.fileExists("segments.gen"))
  589.             return true;
  590.          
  591.         IndexSearcher indexSearcher=new IndexSearcher(directory);
  592.         TermQuery query=new TermQuery(new Term("md5code", md5code));
  593.         BooleanQuery booleanQuery=new BooleanQuery();
  594.         booleanQuery.add(query,Occur.MUST);
  595.          
  596.         TopDocs docs=indexSearcher.search(query, 1);
  597.         for(ScoreDoc scoredoc:docs.scoreDocs){
  598.             Document document=indexSearcher.doc(scoredoc.doc);
  599.             
  600.             String store=document.get("store");
  601.             if("f".equals(store))
  602.                 return false;
  603.             
  604.             String contenthash=document.get("md5contentcode");
  605.             if(contentMD5.equals(contenthash))
  606.             {
  607.                 logger.debug("页面内容没有变化"+document.get("url"));
  608.                 return false;
  609.             }
  610.         }
  611.          
  612.         return true;
  613.     }
  614.      
  615.     /**
  616.      *
  617.      * @param datas 关键字  时间范围  分组
  618.      * @return
  619.      * @throws IOException
  620.      */
  621.     public LucenePage  search(LucenePage page,String... datas) throws IOException,RemoteException{
  622.          
  623.         IndexSearcher indexSearcher=new IndexSearcher(directory);
  624.          
  625.          BooleanQuery booleanQuery=new BooleanQuery();
  626.          
  627.          Filter filter=null;
  628.          
  629.          int start=0;
  630.          int end=10;
  631.          
  632.          //分页
  633.          if(page!=null){
  634.              start=(page.getPageNo()-1)*page.getPageSize();
  635.              end=start+page.getPageSize();
  636.          }
  637.          if(datas[0]!=null&&"1".equals(datas[0])){
  638.              booleanQuery.add(new TermQuery(new Term("shenhe","1")),Occur.MUST);//查询审核过的
  639.          }
  640.          
  641.          if(datas[1]!=null
  642.                  &&!"".equals(datas[1].trim())){
  643.                      
  644.                     char chars[]=datas[1].toCharArray();
  645.                     if(datas[1].length()>2){
  646.                         BooleanQuery booleanQuery2=new BooleanQuery();
  647.                         for(int i=0;i<chars.length-1;i++){
  648.                             booleanQuery2.add(new TermQuery(new Term("content",new String(chars, i,2))), Occur.MUST);   
  649.                         }
  650.                         booleanQuery.add(booleanQuery2, Occur.MUST);
  651.                     }else
  652.                         booleanQuery.add(new FuzzyQuery(new Term("content", datas[1])),Occur.MUST);
  653.                     }
  654.         if(datas.length>2&&datas[2]!=null&&datas[3]!=null){
  655.             
  656.             if(!"".equals(datas[2])&&!"".equals(datas[3]))
  657.             {
  658.               try {
  659.                 filter=new RangeFilter("ctime",
  660.                           ""+dateFormat.parse(datas[2]).getTime(),
  661.                           ""+dateFormat.parse(datas[3]).getTime(),
  662.                           true, true);
  663.             } catch (java.text.ParseException e) {
  664.                 e.printStackTrace();
  665.             }
  666.             }
  667.                
  668.         }
  669.         if(datas.length>3&&datas[4]!=null){
  670.             try {
  671.                 booleanQuery.add(new QueryParser("group",analyzer).parse(datas[4]),Occur.MUST);
  672.             } catch (ParseException e) {
  673.                 e.printStackTrace();
  674.             }
  675.         }
  676.          
  677.         List<String[]>  results=new ArrayList<String[]>();
  678.          
  679.         booleanQuery.add(new TermQuery(new Term("store", "t")),Occur.MUST);

  680.          Sort sort=new Sort(new SortField[]{
  681.                  new SortField("ctime",SortField.LONG,true),
  682.                  new SortField("content",SortField.SCORE),
  683.                  new SortField("score",SortField.INT,true),
  684.                  });         
  685.         TopFieldDocs topFieldDocs=indexSearcher.search(booleanQuery, filter, maxresult, sort);
  686.         page.setTotal(topFieldDocs.totalHits);
  687.         if(topFieldDocs!=null&&topFieldDocs.scoreDocs.length>0){
  688.             for(int i=start;i<end&&i<topFieldDocs.scoreDocs.length;i++){
  689.                  
  690.                 ScoreDoc scoreDoc=topFieldDocs.scoreDocs[i];
  691.                 Document document=indexSearcher.doc(scoreDoc.doc);
  692.                  
  693.                 String[] one_result=new String[8];
  694.                 results.add(one_result);
  695.                 one_result[0]=document.get("url");
  696.                 one_result[1]=document.get("title");
  697.                 Date date=new Date();
  698.                 date.setTime(Long.parseLong(document.get("ctime")));
  699.                 one_result[2]=dateFormat.format(date);
  700.                 one_result[3]=document.get("id");
  701.                 one_result[4]=document.get("shenhe");
  702.                 one_result[5]=document.get("group");
  703.                 one_result[6]=document.get("keyword");
  704.                 one_result[7]=document.get("score");
  705.             }
  706.             
  707.         }
  708.          page.setResult(results);
  709.          indexSearcher.close();
  710.          return page;
  711.     }
  712.      
  713.     @Override
  714.     public List<Map<String, Object>> getLuceneData(String ids)
  715.             throws RemoteException,IOException {
  716.          
  717.         List<Map<String, Object>> dataMap=new ArrayList<Map<String,Object>>();
  718.         if(!directory.fileExists("segments.gen"))
  719.             return dataMap;
  720.          
  721.         String id_s[]=null;
  722.         if(ids!=null){
  723.             id_s=ids.split(",");
  724.         }
  725.          
  726.         if(id_s!=null){
  727.             
  728.             BooleanQuery booleanQuery=new BooleanQuery();
  729.             IndexSearcher indexSearcher=new IndexSearcher(directory);
  730.             for(int i=0;i<id_s.length;i++){
  731.                 booleanQuery.add(new TermQuery(new Term("id",id_s[i])),Occur.SHOULD);
  732.             }
  733.             TopDocs docs=indexSearcher.search(booleanQuery,id_s.length);
  734.             for(ScoreDoc scoredoc:docs.scoreDocs){
  735.                 Document document=indexSearcher.doc(scoredoc.doc);
  736.                 Map<String, Object> map=new HashMap<String, Object>();
  737.                 dataMap.add(map);
  738.                 map.put("atitle", document.get("title"));               
  739.                 map.put("url",  document.get("url"));
  740.                 Date date=new Date();
  741.                 long t=Long.parseLong(document.get("ctime"));
  742.                 date.setTime(t);
  743.                 map.put("adate", dateFormat.format(date) );
  744.                 map.put("fromarea",  document.get("title"));
  745.                  
  746.             }
  747.             indexSearcher.close();
  748.         }
  749.         return dataMap;
  750.          
  751.     }
  752.      
  753.     public String processUrl(String url,String parenturl){
  754.      
  755.         //取出主机地址
  756.         Pattern pattern_host=Pattern.compile("http://\\w+\\.\\w+\\.\\w+");
  757.          
  758.         Pattern pattern=Pattern.compile("^\\w+/\\w+/");
  759.         Pattern pattern2=Pattern.compile("^\\.\\./\\w+");
  760.         Matcher matcher_host=pattern_host.matcher(parenturl);
  761.         Matcher matcher=pattern.matcher(url);
  762.         String host=null;

  763.         if(parenturl.endsWith("/"))
  764.             parenturl=parenturl.substring(0,parenturl.length()-1);
  765.         if(url.endsWith("/"))
  766.             url=url.substring(0,url.length()-1);
  767.         if(matcher_host.find())
  768.             host=matcher_host.group();
  769.          
  770.          if(host==null)
  771.              return url;
  772.          
  773.         if(url.startsWith("/"))
  774.             return host+url.substring(1);
  775.          
  776.         else if(url.startsWith("./"))
  777.             return parenturl+"/"+url.substring(1);
  778.      
  779.         else if(matcher.find()||
  780.                 url.startsWith("../")){
  781.             
  782.             Matcher matcher2=pattern2.matcher(url);
  783.             while(matcher2.find()){
  784.                 url=url.substring(3);
  785.                 parenturl=parenturl.substring(0, parenturl.lastIndexOf("/")-1);
  786.                 parenturl=parenturl.substring(0, parenturl.lastIndexOf("/"));
  787.             }
  788.             
  789.             return parenturl+"/"+url;
  790.         }
  791.         if(url.startsWith("#")||url.startsWith("javascript"))
  792.             return parenturl;
  793.         return url;
  794.     }
  795.      
  796.     /**
  797.      * MD5
  798.      * @param plainText
  799.      * @return
  800.      */
  801.     public static String md5(String plainText) {
  802.         try {
  803.          MessageDigest md = MessageDigest.getInstance("MD5");
  804.          md.update(plainText.getBytes());
  805.          byte b[] = md.digest();

  806.          int i;

  807.          StringBuffer buf = new StringBuffer();
  808.          for (int offset = 0; offset < b.length; offset++) {
  809.           i = b[offset];
  810.           if (i < 0)
  811.            i += 256;
  812.           if (i < 16)
  813.            buf.append("0");
  814.           buf.append(Integer.toHexString(i));
  815.          }
  816.          
  817.           return buf.toString().substring(8, 24);
  818.         } catch (NoSuchAlgorithmException e) {
  819.          e.printStackTrace();
  820.         }
  821.         return  null;
  822.        }

  823.     public IListInfoDAO getHalleyCurrencyDao() {
  824.         return halleyCurrencyDao;
  825.     }

  826.     public void setHalleyCurrencyDao(IListInfoDAO halleyCurrencyDao) {
  827.         this.halleyCurrencyDao = halleyCurrencyDao;
  828.     }
  829.     public static class IndexInfo{
  830.       private int score;
  831.       private int type;
  832.       private   String string;
  833.       private   String url;
  834.       private String title;
  835.       private String group;
  836.       private String keyword;
  837.       private   boolean shenhe;
  838.       private   boolean store;
  839.     //当前关键字分组
  840.       private String[] group_keyword;
  841.       
  842.     }

  843.     public static void main(String[] args){
  844.         Logger logger=Logger.getLogger("");
  845.         logger.info("nihao");
  846.     }
  847.     @Override
  848.     public void shenhe(String id) throws IOException, RemoteException {
  849.         shenHeById(id);
  850.     }
  851.      
  852. }
复制代码

论坛徽章:
59
2015七夕节徽章
日期:2015-08-24 11:17:25ChinaUnix专家徽章
日期:2015-07-20 09:19:30每周论坛发贴之星
日期:2015-07-20 09:19:42ChinaUnix元老
日期:2015-07-20 11:04:38荣誉版主
日期:2015-07-20 11:05:19巳蛇
日期:2015-07-20 11:05:26CU十二周年纪念徽章
日期:2015-07-20 11:05:27IT运维版块每日发帖之星
日期:2015-07-20 11:05:34操作系统版块每日发帖之星
日期:2015-07-20 11:05:36程序设计版块每日发帖之星
日期:2015-07-20 11:05:40数据库技术版块每日发帖之星
日期:2015-07-20 11:05:432015年辞旧岁徽章
日期:2015-07-20 11:05:44
2 [报告]
发表于 2015-08-12 11:14 |只看该作者
楼主想要抓取什么?
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP