Distributed Peer-to-Peer Web Search Engine and Intranet Search Appliance
Java decentralizedintranet-searchintranet-search-enginep2pp2p-networkprivacyprivacy-protectionsearch-enginesearchenginewebweb-search-enginewebsearchwebseearch-engine
complete redesign of search process: - removed 'worker' processes - no internal time-out behaviour: methods either are successful or return null - waiting is only done on top-level - removed snippet-production; this is replaced by solr snippets - removed statistics based on solr size queries (they had been VERY long); the statistics (like suggestions or tag cloud) are now again based on the old but very fast RWI index. In portal or intranet mode the RWI index is usually switched off; if you like to have statistics again then you must switch on the rwis again in this mode. - fixed many bugs regarding correct page counter
Michael Peter Christenc95a84103a45
diff --git a/htroot/AccessTracker_p.java b/htroot/AccessTracker_p.javaindex 103fc7ee1..fd0c4a094 100644--- a/htroot/AccessTracker_p.java+++ b/htroot/AccessTracker_p.java@@ -173,23 +173,25 @@ public class AccessTracker_p {}prop.putNum("page_list_" + m + "_querycount", query.itemsPerPage);prop.putNum("page_list_" + m + "_transmitcount", query.transmitcount);- prop.putNum("page_list_" + m + "_resultcount", query.getResultCount());+ prop.putNum("page_list_" + m + "_resultcount", 0 /*query.getResultCount()*/);prop.putNum("page_list_" + m + "_urltime", query.urlretrievaltime);prop.putNum("page_list_" + m + "_snippettime", query.snippetcomputationtime);prop.putNum("page_list_" + m + "_resulttime", query.searchtime);prop.putHTML("page_list_" + m + "_userAgent", query.userAgent);qcountSum += query.itemsPerPage;- rcountSum += query.getResultCount();+ rcountSum += 0; //query.getResultCount();tcountSum += query.transmitcount;utimeSum += query.urlretrievaltime;stimeSum += query.snippetcomputationtime;rtimeSum += query.searchtime;+ /*if (query.getResultCount() > 0){rcount++;utimeSum1 += query.urlretrievaltime;stimeSum1 += query.snippetcomputationtime;rtimeSum1 += query.searchtime;}+ */m++;}prop.put("page_list", m);diff --git a/htroot/IndexControlRWIs_p.java b/htroot/IndexControlRWIs_p.javaindex 8b16efa76..152e8c0ac 100644--- a/htroot/IndexControlRWIs_p.java+++ b/htroot/IndexControlRWIs_p.java@@ -63,7 +63,6 @@ import net.yacy.search.Switchboard;import net.yacy.search.SwitchboardConstants;import net.yacy.search.index.Segment;import net.yacy.search.query.QueryParams;-import net.yacy.search.query.RankingProcess;import net.yacy.search.query.SearchEvent;import net.yacy.search.query.SearchEventCache;import net.yacy.search.ranking.BlockRank;@@ -126,7 +125,7 @@ public class IndexControlRWIs_p {if ( post.containsKey("keystringsearch") ) {prop.put("keyhash", keyhash);final SearchEvent theSearch = genSearchresult(prop, sb, segment, keyhash, null);- if (theSearch.query.local_rwi_available.get() == 0) {+ if (theSearch.local_rwi_available.get() == 0) {prop.put("searchresult", 1);prop.putHTML("searchresult_word", keystring);}@@ -137,7 +136,7 @@ public class IndexControlRWIs_p {prop.put("keystring", "<" + errmsg + ">");}final SearchEvent theSearch = genSearchresult(prop, sb, segment, keyhash, null);- if (theSearch.query.local_rwi_available.get() == 0) {+ if (theSearch.local_rwi_available.get() == 0) {prop.put("searchresult", 2);prop.putHTML("searchresult_wordhash", ASCII.String(keyhash));}@@ -464,7 +463,7 @@ public class IndexControlRWIs_p {final String keyhashs = ASCII.String(keyhash);prop.put("genUrlList_keyHash", keyhashs);- if (theSearch.query.local_rwi_stored.get() == 0) {+ if (theSearch.local_rwi_stored.get() == 0) {prop.put("genUrlList", 1);prop.put("genUrlList_count", 0);prop.put("searchresult", 2);@@ -478,7 +477,7 @@ public class IndexControlRWIs_p {URIMetadataNode entry;String us;long rn = -1;- while ( !theSearch.rankingProcess.rwiIsEmpty() && (entry = theSearch.takeURL(false, 1000)) != null ) {+ while (!theSearch.rwiIsEmpty() && (entry = theSearch.pullOneFilteredFromRWI(false)) != null) {url = entry.url();if ( url == null ) {continue;@@ -505,9 +504,9 @@ public class IndexControlRWIs_p {prop.putNum("genUrlList_urlList_" + i + "_urlExists_tf", 1000.0 * entry.word().termFrequency());- prop.putNum("genUrlList_urlList_" + i + "_urlExists_authority", (theSearch.rankingProcess.getOrder() == null)+ prop.putNum("genUrlList_urlList_" + i + "_urlExists_authority", (theSearch.getOrder() == null)? -1- : theSearch.rankingProcess.getOrder().authority(ASCII.String(entry.hash(), 6, 6)));+ : theSearch.getOrder().authority(ASCII.String(entry.hash(), 6, 6)));prop.put("genUrlList_urlList_" + i + "_urlExists_date",GenericFormatter.SHORT_DAY_FORMATTER.format(new Date(entry.word().lastModified())));@@ -550,7 +549,7 @@ public class IndexControlRWIs_p {break;}}- final Iterator<byte[]> iter = theSearch.query.misses.iterator(); // iterates url hash strings+ final Iterator<byte[]> iter = theSearch.misses.iterator(); // iterates url hash stringsbyte[] b;while ( iter.hasNext() ) {b = iter.next();@@ -651,26 +650,25 @@ public class IndexControlRWIs_p {String khw = ASCII.String(keyhash);final QueryParams query = new QueryParams(khw, khw, -1, filter, segment, sb.getRanking(), "IndexControlRWIs_p");final SearchEvent theSearch = SearchEventCache.getEvent(query, sb.peers, sb.tables, null, false, sb.loader, Integer.MAX_VALUE, Long.MAX_VALUE, (int) sb.getConfigLong(SwitchboardConstants.DHT_BURST_ROBINSON, 0), (int) sb.getConfigLong(SwitchboardConstants.DHT_BURST_MULTIWORD, 0));- //theSearch.rankingProcess.run();- RankingProcess ranked = theSearch.rankingProcess;- if (theSearch.query.local_rwi_available.get() == 0) {+ if (theSearch.rwiProcess != null && theSearch.rwiProcess.isAlive()) try {theSearch.rwiProcess.join();} catch (InterruptedException e) {}+ if (theSearch.local_rwi_available.get() == 0) {prop.put("searchresult", 2);prop.put("searchresult_wordhash", keyhash);} else {prop.put("searchresult", 3);- prop.put("searchresult_allurl", theSearch.query.local_rwi_available.get());+ prop.put("searchresult_allurl", theSearch.local_rwi_available.get());prop- .put("searchresult_description", ranked.flagCount()[WordReferenceRow.flag_app_dc_description]);- prop.put("searchresult_title", ranked.flagCount()[WordReferenceRow.flag_app_dc_title]);- prop.put("searchresult_creator", ranked.flagCount()[WordReferenceRow.flag_app_dc_creator]);- prop.put("searchresult_subject", ranked.flagCount()[WordReferenceRow.flag_app_dc_subject]);- prop.put("searchresult_url", ranked.flagCount()[WordReferenceRow.flag_app_dc_identifier]);- prop.put("searchresult_emphasized", ranked.flagCount()[WordReferenceRow.flag_app_emphasized]);- prop.put("searchresult_image", ranked.flagCount()[Condenser.flag_cat_hasimage]);- prop.put("searchresult_audio", ranked.flagCount()[Condenser.flag_cat_hasaudio]);- prop.put("searchresult_video", ranked.flagCount()[Condenser.flag_cat_hasvideo]);- prop.put("searchresult_app", ranked.flagCount()[Condenser.flag_cat_hasapp]);- prop.put("searchresult_indexof", ranked.flagCount()[Condenser.flag_cat_indexof]);+ .put("searchresult_description", theSearch.flagCount()[WordReferenceRow.flag_app_dc_description]);+ prop.put("searchresult_title", theSearch.flagCount()[WordReferenceRow.flag_app_dc_title]);+ prop.put("searchresult_creator", theSearch.flagCount()[WordReferenceRow.flag_app_dc_creator]);+ prop.put("searchresult_subject", theSearch.flagCount()[WordReferenceRow.flag_app_dc_subject]);+ prop.put("searchresult_url", theSearch.flagCount()[WordReferenceRow.flag_app_dc_identifier]);+ prop.put("searchresult_emphasized", theSearch.flagCount()[WordReferenceRow.flag_app_emphasized]);+ prop.put("searchresult_image", theSearch.flagCount()[Condenser.flag_cat_hasimage]);+ prop.put("searchresult_audio", theSearch.flagCount()[Condenser.flag_cat_hasaudio]);+ prop.put("searchresult_video", theSearch.flagCount()[Condenser.flag_cat_hasvideo]);+ prop.put("searchresult_app", theSearch.flagCount()[Condenser.flag_cat_hasapp]);+ prop.put("searchresult_indexof", theSearch.flagCount()[Condenser.flag_cat_indexof]);}return theSearch;}diff --git a/htroot/js/yacysearch.js b/htroot/js/yacysearch.jsindex df327002f..5c467c27f 100644--- a/htroot/js/yacysearch.js+++ b/htroot/js/yacysearch.js@@ -75,11 +75,10 @@ function statistics(offset, itemscount, itemsperpage, totalcount, localResourceSif (offset >= 0) document.getElementById("resultsOffset").firstChild.nodeValue = offset;if (itemscount >= 0) document.getElementById("itemscount").firstChild.nodeValue = itemscount;document.getElementById("totalcount").firstChild.nodeValue = totalcount;- if (document.getElementById("localResourceSize") == null) return;- document.getElementById("localResourceSize").firstChild.nodeValue = localResourceSize;- document.getElementById("remoteResourceSize").firstChild.nodeValue = remoteResourceSize;- document.getElementById("remoteIndexCount").firstChild.nodeValue = remoteIndexCount;- document.getElementById("remotePeerCount").firstChild.nodeValue = remotePeerCount;+ if (document.getElementById("localResourceSize") != null) document.getElementById("localResourceSize").firstChild.nodeValue = localResourceSize;+ if (document.getElementById("remoteResourceSize") != null) document.getElementById("remoteResourceSize").firstChild.nodeValue = remoteResourceSize;+ if (document.getElementById("remoteIndexCount") != null) document.getElementById("remoteIndexCount").firstChild.nodeValue = remoteIndexCount;+ if (document.getElementById("remotePeerCount") != null) document.getElementById("remotePeerCount").firstChild.nodeValue = remotePeerCount;document.getElementById("resNav").firstChild.nodeValue = "X";// compose page navigation@@ -93,7 +92,7 @@ function statistics(offset, itemscount, itemsperpage, totalcount, localResourceSresnav += ("\"><img src=\"env/grafics/navdl.gif\" alt=\"arrowleft\" width=\"16\" height=\"16\" /></a> ");}- numberofpages = Math.min(10, 1 + ((totalcount - 1) / itemsperpage));+ numberofpages = Math.floor(Math.min(10, 1 + ((totalcount - 1) / itemsperpage)));if (!numberofpages) numberofpages = 10;for (i = 0; i < numberofpages; i++) {if (i == thispage) {diff --git a/htroot/suggest.java b/htroot/suggest.javaindex a4c03ad4b..e86b5984f 100644--- a/htroot/suggest.java+++ b/htroot/suggest.java@@ -67,7 +67,7 @@ public class suggest {final int count = (post == null) ? 10 : Math.min(20, post.getInt("count", 10));int c = 0;- if (more || (sb.index.getQueryCount(querystring) == 0)) {+ if (more || (sb.index.getWordCountGuess(querystring) == 0)) {final DidYouMean didYouMean = new DidYouMean(sb.index, new StringBuilder(querystring));final SortedSet<StringBuilder> suggestions = didYouMean.getSuggestions(timeout, count);//[#[query]#,[#{suggestions}##[text]##(eol)#,::#(/eol)##{/suggestions}#]]diff --git a/htroot/yacy/search.java b/htroot/yacy/search.javaindex 9272db816..52875ab61 100644--- a/htroot/yacy/search.java+++ b/htroot/yacy/search.java@@ -44,6 +44,7 @@ import net.yacy.cora.lod.vocabulary.Tagging;import net.yacy.cora.protocol.Domains;import net.yacy.cora.protocol.HeaderFramework;import net.yacy.cora.protocol.RequestHeader;+import net.yacy.cora.sorting.ConcurrentScoreMap;import net.yacy.cora.sorting.ScoreMap;import net.yacy.cora.sorting.WeakPriorityBlockingQueue;import net.yacy.cora.storage.HandleSet;@@ -323,13 +324,14 @@ public final class search {// make eventtheSearch = SearchEventCache.getEvent(theQuery, sb.peers, sb.tables, null, abstracts.length() > 0, sb.loader, count, maxtime, (int) sb.getConfigLong(SwitchboardConstants.DHT_BURST_ROBINSON, 0), (int) sb.getConfigLong(SwitchboardConstants.DHT_BURST_MULTIWORD, 0));+ if (theSearch.rwiProcess != null && theSearch.rwiProcess.isAlive()) try {theSearch.rwiProcess.join();} catch (InterruptedException e) {}// set statistic details of search result and find best result index set- prop.put("joincount", Integer.toString(theQuery.getResultCount()));- if (theQuery.getResultCount() > 0) {+ prop.put("joincount", Integer.toString(theSearch.getResultCount()));+ if (theSearch.getResultCount() > 0) {accu = theSearch.completeResults(maxtime);}- if (theQuery.getResultCount() <= 0 || abstracts.isEmpty()) {+ if (theSearch.getResultCount() <= 0 || abstracts.isEmpty()) {prop.put("indexcount", "");} else {// attach information about index abstracts@@ -375,7 +377,7 @@ public final class search {// prepare reference hintsfinal long timer = System.currentTimeMillis();- final ScoreMap<String> topicNavigator = theSearch.rankingProcess.getTopics(5, 100);+ final ScoreMap<String> topicNavigator = sb.index.connectedRWI() ? theSearch.getTopics(5, 100) : new ConcurrentScoreMap<String>();final StringBuilder refstr = new StringBuilder(6000);final Iterator<String> navigatorIterator = topicNavigator.keys(false);int i = 0;@@ -391,7 +393,8 @@ public final class search {prop.put("indexabstract", indexabstract.toString());// prepare result- if (theQuery.getResultCount() == 0 || accu == null || accu.isEmpty()) {+ int resultCount = theSearch.getResultCount();+ if (resultCount == 0 || accu == null || accu.isEmpty()) {// no resultsprop.put("links", "");@@ -422,7 +425,7 @@ public final class search {theQuery.searchtime = System.currentTimeMillis() - timestamp;theQuery.urlretrievaltime = (theSearch == null) ? 0 : theSearch.getURLRetrievalTime();theQuery.snippetcomputationtime = (theSearch == null) ? 0 : theSearch.getSnippetComputationTime();- AccessTracker.add(AccessTracker.Location.remote, theQuery);+ AccessTracker.add(AccessTracker.Location.remote, theQuery, resultCount);// update the search trackersynchronized (trackerHandles) {@@ -435,7 +438,7 @@ public final class search {// logNetwork.log.logInfo("EXIT HASH SEARCH: " +- QueryParams.anonymizedQueryHashes(theQuery.getQueryGoal().getIncludeHashes()) + " - " + theQuery.getResultCount() + " links found, " ++ QueryParams.anonymizedQueryHashes(theQuery.getQueryGoal().getIncludeHashes()) + " - " + resultCount + " links found, " +prop.get("linkcount", "?") + " links selected, " +indexabstractContainercount + " index abstracts, " +(System.currentTimeMillis() - timestamp) + " milliseconds");diff --git a/htroot/yacysearch.java b/htroot/yacysearch.javaindex c6f5a7841..6be8297b6 100644--- a/htroot/yacysearch.java+++ b/htroot/yacysearch.java@@ -731,14 +731,14 @@ public class yacysearch {Log.logInfo("LOCAL_SEARCH", "EXIT WORD SEARCH: "+ theQuery.getQueryGoal().getOriginalQueryString(false)+ " - "- + "local_rwi_available(" + theSearch.query.local_rwi_available.get() + "), "- + "local_rwi_stored(" + theSearch.query.local_rwi_stored.get() + "), "- + "local_solr_available(" + theSearch.query.local_solr_available.get() + "), "- + "local_solr_stored(" + theSearch.query.local_solr_stored.get() + "), "- + "remote_available(" + theSearch.query.remote_available.get() + "), "- + "remote_stored(" + theSearch.query.remote_stored.get() + "), "- + "remote_peerCount(" + theSearch.query.remote_peerCount.get() + "), "- + "local_sortout(" + theSearch.query.misses.size() + "), "+ + "local_rwi_available(" + theSearch.local_rwi_available.get() + "), "+ + "local_rwi_stored(" + theSearch.local_rwi_stored.get() + "), "+ + "local_solr_available(" + theSearch.local_solr_available.get() + "), "+ + "local_solr_stored(" + theSearch.local_solr_stored.get() + "), "+ + "remote_available(" + theSearch.remote_available.get() + "), "+ + "remote_stored(" + theSearch.remote_stored.get() + "), "+ + "remote_peerCount(" + theSearch.remote_peerCount.get() + "), "+ + "local_sortout(" + theSearch.misses.size() + "), "+ (System.currentTimeMillis() - timestamp)+ " ms");@@ -746,13 +746,13 @@ public class yacysearch {theQuery.searchtime = System.currentTimeMillis() - timestamp;theQuery.urlretrievaltime = theSearch.getURLRetrievalTime();theQuery.snippetcomputationtime = theSearch.getSnippetComputationTime();- AccessTracker.add(AccessTracker.Location.local, theQuery);+ AccessTracker.add(AccessTracker.Location.local, theQuery, theSearch.getResultCount());// check suggestionsfinal int meanMax = (post != null) ? post.getInt("meanCount", 0) : 0;prop.put("meanCount", meanMax);- if ( meanMax > 0 && !json && !rss ) {+ if ( meanMax > 0 && !json && !rss && sb.index.connectedRWI()) {final DidYouMean didYouMean = new DidYouMean(indexSegment, new StringBuilder(querystring));final Iterator<StringBuilder> meanIt = didYouMean.getSuggestions(100, 5).iterator();int meanCount = 0;@@ -822,15 +822,15 @@ public class yacysearch {}prop.put("num-results_offset", startRecord == 0 ? 0 : startRecord + 1);- prop.put("num-results_itemscount", Formatter.number(startRecord + theSearch.query.itemsPerPage > theSearch.query.getResultCount() ? startRecord + theSearch.query.getResultCount() % theSearch.query.itemsPerPage : startRecord + theSearch.query.itemsPerPage, true));+ prop.put("num-results_itemscount", Formatter.number(startRecord + theSearch.query.itemsPerPage > theSearch.getResultCount() ? startRecord + theSearch.getResultCount() % theSearch.query.itemsPerPage : startRecord + theSearch.query.itemsPerPage, true));prop.put("num-results_itemsPerPage", Formatter.number(itemsPerPage));- prop.put("num-results_totalcount", Formatter.number(theSearch.query.getResultCount()));+ prop.put("num-results_totalcount", Formatter.number(theSearch.getResultCount()));prop.put("num-results_globalresults", global && (indexReceiveGranted || clustersearch) ? "1" : "0");- prop.put("num-results_globalresults_localResourceSize", Formatter.number(theSearch.query.local_rwi_available.get() + theSearch.query.local_solr_available.get(), true));- prop.put("num-results_globalresults_localMissCount", Formatter.number(theSearch.query.misses.size(), true));- prop.put("num-results_globalresults_remoteResourceSize", Formatter.number(theSearch.query.remote_available.get(), true));- prop.put("num-results_globalresults_remoteIndexCount", Formatter.number(theSearch.query.remote_stored.get(), true));- prop.put("num-results_globalresults_remotePeerCount", Formatter.number(theSearch.query.remote_peerCount.get(), true));+ prop.put("num-results_globalresults_localResourceSize", Formatter.number(theSearch.local_rwi_available.get() + theSearch.local_solr_available.get(), true));+ prop.put("num-results_globalresults_localMissCount", Formatter.number(theSearch.misses.size(), true));+ prop.put("num-results_globalresults_remoteResourceSize", Formatter.number(theSearch.remote_available.get(), true));+ prop.put("num-results_globalresults_remoteIndexCount", Formatter.number(theSearch.remote_stored.get(), true));+ prop.put("num-results_globalresults_remotePeerCount", Formatter.number(theSearch.remote_peerCount.get(), true));// compose page navigationfinal StringBuilder resnav = new StringBuilder(200);@@ -844,7 +844,7 @@ public class yacysearch {resnav.append("\"><img src=\"env/grafics/navdl.gif\" alt=\"arrowleft\" width=\"16\" height=\"16\" /></a> ");}- final int numberofpages = Math.min(10, 1 + ((theSearch.query.getResultCount() - 1) / theQuery.itemsPerPage()));+ final int numberofpages = Math.min(10, 1 + ((theSearch.getResultCount() - 1) / theQuery.itemsPerPage()));for ( int i = 0; i < numberofpages; i++ ) {if ( i == thispage ) {@@ -873,7 +873,7 @@ public class yacysearch {}final String resnavs = resnav.toString();prop.put("num-results_resnav", resnavs);- prop.put("pageNavBottom", (theSearch.query.getResultCount() - startRecord > 6) ? 1 : 0); // if there are more results than may fit on the page we add a navigation at the bottom+ prop.put("pageNavBottom", (theSearch.getResultCount() - startRecord > 6) ? 1 : 0); // if there are more results than may fit on the page we add a navigation at the bottomprop.put("pageNavBottom_resnav", resnavs);// generate the search result lines; the content will be produced by another servletdiff --git a/htroot/yacysearchitem.java b/htroot/yacysearchitem.javaindex 96dde5ccf..8e4d6d312 100644--- a/htroot/yacysearchitem.java+++ b/htroot/yacysearchitem.java@@ -94,14 +94,14 @@ public class yacysearchitem {// dynamically update count valuesprop.put("offset", theSearch.query.neededResults() - theSearch.query.itemsPerPage() + 1);- prop.put("itemscount", Formatter.number(Math.min((item < 0) ? theSearch.query.neededResults() : item + 1, theSearch.query.getResultCount())));+ prop.put("itemscount", Formatter.number(Math.min((item < 0) ? theSearch.query.neededResults() : item + 1, theSearch.getResultCount())));prop.put("itemsperpage", Formatter.number(theSearch.query.itemsPerPage));- prop.put("totalcount", Formatter.number(theSearch.query.getResultCount(), true));- prop.put("localResourceSize", Formatter.number(theSearch.query.local_rwi_available.get() + theSearch.query.local_solr_available.get(), true));- prop.put("localMissCount", Formatter.number(theSearch.query.misses.size(), true));- prop.put("remoteResourceSize", Formatter.number(theSearch.query.remote_stored.get(), true));- prop.put("remoteIndexCount", Formatter.number(theSearch.query.remote_available.get(), true));- prop.put("remotePeerCount", Formatter.number(theSearch.query.remote_peerCount.get(), true));+ prop.put("totalcount", Formatter.number(theSearch.getResultCount(), true));+ prop.put("localResourceSize", Formatter.number(theSearch.local_rwi_available.get() + theSearch.local_solr_available.get(), true));+ prop.put("localMissCount", Formatter.number(theSearch.misses.size(), true));+ prop.put("remoteResourceSize", Formatter.number(theSearch.remote_stored.get(), true));+ prop.put("remoteIndexCount", Formatter.number(theSearch.remote_available.get(), true));+ prop.put("remotePeerCount", Formatter.number(theSearch.remote_peerCount.get(), true));prop.put("navurlBase", QueryParams.navurlBase("html", theSearch.query, null).toString());final String target_special_pattern = sb.getConfig(SwitchboardConstants.SEARCH_TARGET_SPECIAL_PATTERN, "");@@ -109,7 +109,7 @@ public class yacysearchitem {// text search// generate result object- final ResultEntry result = theSearch.oneResult(item, theSearch.query.isLocal() ? 1000 : 5000);+ final ResultEntry result = theSearch.oneResult(item, theSearch.query.isLocal() ? 1000 : 3000);if (result == null) return prop; // no contentfinal String resultUrlstring = result.urlstring();final DigestURI resultURL = result.url();diff --git a/htroot/yacysearchlatestinfo.java b/htroot/yacysearchlatestinfo.javaindex faa871256..a5b379dfb 100644--- a/htroot/yacysearchlatestinfo.java+++ b/htroot/yacysearchlatestinfo.java@@ -34,14 +34,14 @@ public class yacysearchlatestinfo {// dynamically update count valuesfinal int offset = theSearch.query.neededResults() - theSearch.query.itemsPerPage() + 1;prop.put("offset", offset);- prop.put("itemscount",Formatter.number(offset + theSearch.query.itemsPerPage >= theSearch.query.getResultCount() ? offset + theSearch.query.getResultCount() % theSearch.query.itemsPerPage - 1 : offset + theSearch.query.itemsPerPage - 1));+ prop.put("itemscount",Formatter.number(offset + theSearch.query.itemsPerPage >= theSearch.getResultCount() ? offset + theSearch.getResultCount() % theSearch.query.itemsPerPage - 1 : offset + theSearch.query.itemsPerPage - 1));prop.put("itemsperpage", theSearch.query.itemsPerPage);- prop.put("totalcount", Formatter.number(theSearch.query.getResultCount(), true));- prop.put("localResourceSize", Formatter.number(theSearch.query.local_rwi_available.get() + theSearch.query.local_solr_available.get(), true));- prop.put("localMissCount", Formatter.number(theSearch.query.misses.size(), true));- prop.put("remoteResourceSize", Formatter.number(theSearch.query.remote_stored.get(), true));- prop.put("remoteIndexCount", Formatter.number(theSearch.query.remote_available.get(), true));- prop.put("remotePeerCount", Formatter.number(theSearch.query.remote_peerCount.get(), true));+ prop.put("totalcount", Formatter.number(theSearch.getResultCount(), true));+ prop.put("localResourceSize", Formatter.number(theSearch.local_rwi_available.get() + theSearch.local_solr_available.get(), true));+ prop.put("localMissCount", Formatter.number(theSearch.misses.size(), true));+ prop.put("remoteResourceSize", Formatter.number(theSearch.remote_stored.get(), true));+ prop.put("remoteIndexCount", Formatter.number(theSearch.remote_available.get(), true));+ prop.put("remotePeerCount", Formatter.number(theSearch.remote_peerCount.get(), true));prop.putJSON("navurlBase", QueryParams.navurlBase("html", theSearch.query, null).toString());return prop;diff --git a/htroot/yacysearchtrailer.java b/htroot/yacysearchtrailer.javaindex acf0ec78e..9899eea9d 100644--- a/htroot/yacysearchtrailer.java+++ b/htroot/yacysearchtrailer.java@@ -35,6 +35,7 @@ import net.yacy.cora.sorting.ScoreMap;import net.yacy.document.LibraryProvider;import net.yacy.peers.graphics.ProfilingGraph;import net.yacy.search.EventTracker;+import net.yacy.search.Switchboard;import net.yacy.search.query.QueryParams;import net.yacy.search.query.SearchEvent;import net.yacy.search.query.SearchEventCache;@@ -51,7 +52,7 @@ public class yacysearchtrailer {public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {final serverObjects prop = new serverObjects();-+ final Switchboard sb = (Switchboard) env;final String eventID = post.get("eventID", "");// find search event@@ -186,7 +187,7 @@ public class yacysearchtrailer {}// topics navigator- final ScoreMap<String> topicNavigator = theSearch.getTopicNavigator(MAX_TOPWORDS);+ final ScoreMap<String> topicNavigator = sb.index.connectedRWI() ? theSearch.getTopicNavigator(MAX_TOPWORDS) : null;if (topicNavigator == null || topicNavigator.isEmpty()) {prop.put("nav-topics", "0");} else {@@ -345,7 +346,7 @@ public class yacysearchtrailer {// about boxfinal String aboutBody = env.getConfig("about.body", "");final String aboutHeadline = env.getConfig("about.headline", "");- if ((aboutBody.isEmpty() && aboutHeadline.isEmpty()) || theSearch.query.getResultCount() == 0) {+ if ((aboutBody.isEmpty() && aboutHeadline.isEmpty()) || theSearch.getResultCount() == 0) {prop.put("nav-about", 0);} else {prop.put("nav-about", 1);@@ -355,7 +356,7 @@ public class yacysearchtrailer {// category: location search// show only if there is a location database present and if there had been any search results- if (LibraryProvider.geoLoc.isEmpty() || theSearch.query.getResultCount() == 0) {+ if (LibraryProvider.geoLoc.isEmpty() || theSearch.getResultCount() == 0) {prop.put("cat-location", 0);} else {prop.put("cat-location", 1);@@ -363,7 +364,7 @@ public class yacysearchtrailer {prop.put(fileType, "cat-location_query", uriginalQuery);prop.put(fileType, "cat-location_queryenc", uriginalQuery.replace(' ', '+'));}- prop.put("num-results_totalcount", theSearch.query.getResultCount());+ prop.put("num-results_totalcount", theSearch.getResultCount());EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(theSearch.query.id(true), SearchEventType.FINALIZATION, "bottomline", 0, 0), false);return prop;}diff --git a/source/net/yacy/cora/federate/solr/connector/EmbeddedSolrConnector.java b/source/net/yacy/cora/federate/solr/connector/EmbeddedSolrConnector.javaindex 98c68331a..dfb369028 100644--- a/source/net/yacy/cora/federate/solr/connector/EmbeddedSolrConnector.java+++ b/source/net/yacy/cora/federate/solr/connector/EmbeddedSolrConnector.java@@ -102,7 +102,7 @@ public class EmbeddedSolrConnector extends SolrServerConnector implements SolrCo* because we can do this with more efficiently in a different way for embedded indexes.*/@Override- public long getSize() {+ public synchronized long getSize() {String threadname = Thread.currentThread().getName();Thread.currentThread().setName("solr query: size");EmbeddedSolrServer ess = (EmbeddedSolrServer) this.server;@@ -154,7 +154,7 @@ public class EmbeddedSolrConnector extends SolrServerConnector implements SolrCoreturn req;}- public SolrQueryResponse query(SolrQueryRequest req) throws SolrException {+ public synchronized SolrQueryResponse query(SolrQueryRequest req) throws SolrException {final long startTime = System.currentTimeMillis();// during the solr query we set the thread name to the query string to get more debugging info in thread dumps@@ -190,7 +190,10 @@ public class EmbeddedSolrConnector extends SolrServerConnector implements SolrCoString q = params.get("q");String threadname = Thread.currentThread().getName();if (q != null) Thread.currentThread().setName("solr query: q = " + q);- QueryResponse rsp = this.server.query(params);+ QueryResponse rsp;+ synchronized (this) {+ rsp = this.server.query(params);+ }if (q != null) Thread.currentThread().setName(threadname);if (rsp != null) log.info(rsp.getResults().size() + " results for q=" + q);return rsp;diff --git a/source/net/yacy/cora/federate/solr/connector/SolrServerConnector.java b/source/net/yacy/cora/federate/solr/connector/SolrServerConnector.javaindex 68e55932b..db9ed7fa9 100644--- a/source/net/yacy/cora/federate/solr/connector/SolrServerConnector.java+++ b/source/net/yacy/cora/federate/solr/connector/SolrServerConnector.java@@ -72,7 +72,7 @@ public abstract class SolrServerConnector extends AbstractSolrConnector implemen* force an explicit merge of segments* @param maxSegments the maximum number of segments. Set to 1 for maximum optimization*/- public void optimize(int maxSegments) {+ public synchronized void optimize(int maxSegments) {try {this.server.optimize(true, true, maxSegments);} catch (Throwable e) {@@ -91,7 +91,7 @@ public abstract class SolrServerConnector extends AbstractSolrConnector implemen}@Override- public long getSize() {+ public synchronized long getSize() {try {final QueryResponse rsp = query(AbstractSolrConnector.catchSuccessQuery);if (rsp == null) return 0;@@ -109,34 +109,28 @@ public abstract class SolrServerConnector extends AbstractSolrConnector implemen* @throws IOException*/@Override- public void clear() throws IOException {+ public synchronized void clear() throws IOException {try {- synchronized (this.server) {- this.server.deleteByQuery("*:*");- this.server.commit(true, true, false);- }+ this.server.deleteByQuery("*:*");+ this.server.commit(true, true, false);} catch (final Throwable e) {throw new IOException(e);}}@Override- public void delete(final String id) throws IOException {+ public synchronized void delete(final String id) throws IOException {try {- synchronized (this.server) {- this.server.deleteById(id, -1);- }+ this.server.deleteById(id, -1);} catch (final Throwable e) {throw new IOException(e);}}@Override- public void delete(final List<String> ids) throws IOException {+ public synchronized void delete(final List<String> ids) throws IOException {try {- synchronized (this.server) {- this.server.deleteById(ids, -1);- }+ this.server.deleteById(ids, -1);} catch (final Throwable e) {throw new IOException(e);}@@ -148,11 +142,9 @@ public abstract class SolrServerConnector extends AbstractSolrConnector implemen* @throws IOException*/@Override- public void deleteByQuery(final String querystring) throws IOException {+ public synchronized void deleteByQuery(final String querystring) throws IOException {try {- synchronized (this.server) {- this.server.deleteByQuery(querystring, -1);- }+ this.server.deleteByQuery(querystring, -1);} catch (final Throwable e) {throw new IOException(e);}@@ -213,7 +205,9 @@ public abstract class SolrServerConnector extends AbstractSolrConnector implemenList<String> ids = new ArrayList<String>();for (SolrInputDocument solrdoc : solrdocs) ids.add((String) solrdoc.getFieldValue(CollectionSchema.id.getSolrFieldName()));try {- this.server.deleteById(ids);+ synchronized (this.server) {+ this.server.deleteById(ids);+ }} catch (SolrServerException e1) {}try {synchronized (this.server) {diff --git a/source/net/yacy/data/DidYouMean.java b/source/net/yacy/data/DidYouMean.javaindex 165334db1..1c27e32af 100644--- a/source/net/yacy/data/DidYouMean.java+++ b/source/net/yacy/data/DidYouMean.java@@ -158,12 +158,12 @@ public class DidYouMean {if (!(scored.sizeSmaller(2 * preSortSelection))) {break;}- scored.inc(s, this.segment.getQueryCount(s));+ scored.inc(s, this.segment.getWordCountGuess(s.toString()));}} catch (ConcurrentModificationException e) {}final SortedSet<StringBuilder> countSorted = Collections.synchronizedSortedSet(new TreeSet<StringBuilder>(new headMatchingComparator(this.word, this.INDEX_SIZE_COMPARATOR)));- final int wc = this.segment.getQueryCount(this.word); // all counts must be greater than this+ final int wc = this.segment.getWordCountGuess(this.word.toString()); // all counts must be greater than thiswhile (!scored.isEmpty() && countSorted.size() < preSortSelection) {final StringBuilder s = scored.getMaxKey();final int score = scored.delete(s);@@ -432,7 +432,7 @@ public class DidYouMean {StringBuilder s;try {while ((s = DidYouMean.this.guessLib.take()) != POISON_STRING) {- if (s.length() >= MinimumOutputWordLength && DidYouMean.this.segment.getQueryCount(s) > 0) {+ if (s.length() >= MinimumOutputWordLength && DidYouMean.this.segment.getWordCountGuess(s.toString()) > 0) {DidYouMean.this.resultSet.add(s);}if (System.currentTimeMillis() > DidYouMean.this.timeLimit) {@@ -451,8 +451,8 @@ public class DidYouMean {@Overridepublic int compare(final StringBuilder o1, final StringBuilder o2) {- final int i1 = DidYouMean.this.segment.getQueryCount(o1);- final int i2 = DidYouMean.this.segment.getQueryCount(o2);+ final int i1 = DidYouMean.this.segment.getWordCountGuess(o1.toString());+ final int i2 = DidYouMean.this.segment.getWordCountGuess(o2.toString());if (i1 == i2) {return WORD_LENGTH_COMPARATOR.compare(o1, o2);}diff --git a/source/net/yacy/kelondro/data/meta/DigestURI.java b/source/net/yacy/kelondro/data/meta/DigestURI.javaindex a6b9dba11..488a781dc 100644--- a/source/net/yacy/kelondro/data/meta/DigestURI.java+++ b/source/net/yacy/kelondro/data/meta/DigestURI.java@@ -210,7 +210,11 @@ public class DigestURI extends MultiProtocolURI implements Serializable {*/public final byte[] hash() {// in case that the object was initialized without a known url hash, compute it now- if (this.hash == null) this.hash = urlHashComputation();+ if (this.hash == null) {+ synchronized (this) {+ if (this.hash == null) this.hash = urlHashComputation();+ }+ }return this.hash;}@@ -394,8 +398,7 @@ public class DigestURI extends MultiProtocolURI implements Serializable {@Overridepublic final boolean isLocal() {if (this.isFile()) return true;- if (this.hash == null) this.hash = urlHashComputation();- return domDomain(this.hash) == 7;+ return domDomain(hash()) == 7;}/**diff --git a/source/net/yacy/peers/Protocol.java b/source/net/yacy/peers/Protocol.javaindex 7487fda49..1a06ab74b 100644--- a/source/net/yacy/peers/Protocol.java+++ b/source/net/yacy/peers/Protocol.java@@ -49,6 +49,7 @@ import java.io.IOException;import java.io.InputStreamReader;import java.net.InetAddress;import java.util.ArrayList;+import java.util.Collection;import java.util.HashMap;import java.util.Iterator;import java.util.LinkedHashMap;@@ -121,6 +122,7 @@ import org.apache.solr.client.solrj.response.QueryResponse;import org.apache.solr.client.solrj.response.FacetField.Count;import org.apache.solr.common.SolrDocument;import org.apache.solr.common.SolrDocumentList;+import org.apache.solr.common.SolrInputDocument;import org.apache.solr.common.params.FacetParams;@@ -760,6 +762,7 @@ public final class Protocol {// insert results to containersint term = count;+ Collection<URIMetadataRow> storeDocs = new ArrayList<URIMetadataRow>(result.links.size());for ( final URIMetadataRow urlEntry : result.links ) {if ( term-- <= 0 ) {break; // do not process more that requested (in case that evil peers fill us up with rubbish)@@ -804,18 +807,13 @@ public final class Protocol {}// passed all checks, store url- try {- event.query.getSegment().fulltext().putMetadata(urlEntry);- ResultURLs.stack(- ASCII.String(urlEntry.url().hash()),- urlEntry.url().getHost(),- event.peers.mySeed().hash.getBytes(),- UTF8.getBytes(target.hash),- EventOrigin.QUERIES);- } catch ( final IOException e ) {- Network.log.logWarning("could not store search result");- continue; // db-error- }+ storeDocs.add(urlEntry);+ ResultURLs.stack(+ ASCII.String(urlEntry.url().hash()),+ urlEntry.url().getHost(),+ event.peers.mySeed().hash.getBytes(),+ UTF8.getBytes(target.hash),+ EventOrigin.QUERIES);if ( urlEntry.snippet() != null&& urlEntry.snippet().length() > 0@@ -837,12 +835,18 @@ public final class Protocol {}}}++ try {+ event.query.getSegment().fulltext().putMetadata(storeDocs);+ } catch ( final IOException e ) {+ Network.log.logWarning("could not store search result", e);+ }// store remote result to local result container// insert one container into the search result buffer// one is enough, only the references are used, not the word- event.rankingProcess.add(container.get(0), false, target.getName() + "/" + target.hash, result.joincount, time);- event.rankingProcess.addFinalize();+ event.addRWIs(container.get(0), false, target.getName() + "/" + target.hash, result.joincount, time);+ event.addFinalize();event.addExpectedRemoteReferences(-count);// insert the containers to the index@@ -858,9 +862,9 @@ public final class Protocol {if ( result.references != null && result.references.length > 0 ) {Network.log.logInfo("remote search: peer " + target.getName() + " sent " + result.references.length + " topics");// add references twice, so they can be counted (must have at least 2 entries)- synchronized ( event.rankingProcess ) {- event.rankingProcess.addTopic(result.references);- event.rankingProcess.addTopic(result.references);+ synchronized (event) {+ event.addTopic(result.references);+ event.addTopic(result.references);}}Network.log.logInfo("remote search: peer " + target.getName() + " sent " + container.get(0).size() + "/" + result.joincount + " references");@@ -1050,7 +1054,7 @@ public final class Protocol {if (localsearch) {// search the local indextry {- rsp = event.rankingProcess.getQuery().getSegment().fulltext().getDefaultConnector().query(solrQuery);+ rsp = event.getQuery().getSegment().fulltext().getDefaultConnector().query(solrQuery);docList = rsp.getResults();} catch (Throwable e) {Network.log.logInfo("SEARCH failed (solr), localpeer (" + e.getMessage() + ")", e);@@ -1114,6 +1118,7 @@ public final class Protocol {Network.log.logInfo("SEARCH (solr), returned " + docList.size() + " out of " + docList.getNumFound() + " documents from " + (target == null ? "shard" : ("peer " + target.hash + ":" + target.getName())));int term = count;+ Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>(docList.size());for (final SolrDocument doc: docList) {if ( term-- <= 0 ) {break; // do not process more that requested (in case that evil peers fill us up with rubbish)@@ -1149,32 +1154,32 @@ public final class Protocol {// passed all checks, store urlif (!localsearch) {- try {- event.query.getSegment().fulltext().putDocument(event.query.getSegment().fulltext().getDefaultConfiguration().toSolrInputDocument(doc));- ResultURLs.stack(- ASCII.String(urlEntry.url().hash()),- urlEntry.url().getHost(),- event.peers.mySeed().hash.getBytes(),- UTF8.getBytes(target.hash),- EventOrigin.QUERIES);- } catch ( final IOException e ) {- Network.log.logWarning("could not store search result", e);- continue; // db-error- }+ docs.add(event.query.getSegment().fulltext().getDefaultConfiguration().toSolrInputDocument(doc));+ ResultURLs.stack(+ ASCII.String(urlEntry.url().hash()),+ urlEntry.url().getHost(),+ event.peers.mySeed().hash.getBytes(),+ UTF8.getBytes(target.hash),+ EventOrigin.QUERIES);}// add the url entry to the word indexescontainer.add(urlEntry);}-+ try {+ event.query.getSegment().fulltext().putDocuments(docs);+ } catch ( final IOException e ) {+ Network.log.logWarning("could not store search result", e);+ }+if (localsearch) {- event.add(container, facets, snippets, true, "localpeer", (int) docList.getNumFound());- event.rankingProcess.addFinalize();+ event.addNodes(container, facets, snippets, true, "localpeer", (int) docList.getNumFound());+ event.addFinalize();event.addExpectedRemoteReferences(-count);Network.log.logInfo("local search (solr): localpeer sent " + container.get(0).size() + "/" + docList.size() + " references");} else {- event.add(container, facets, snippets, false, target.getName() + "/" + target.hash, (int) docList.getNumFound());- event.rankingProcess.addFinalize();+ event.addNodes(container, facets, snippets, false, target.getName() + "/" + target.hash, (int) docList.getNumFound());+ event.addFinalize();event.addExpectedRemoteReferences(-count);Network.log.logInfo("remote search (solr): peer " + target.getName() + " sent " + (container.size() == 0 ? 0 : container.get(0).size()) + "/" + docList.size() + " references");}diff --git a/source/net/yacy/peers/RemoteSearch.java b/source/net/yacy/peers/RemoteSearch.javaindex 1d98d80ee..f7d4f16fd 100644--- a/source/net/yacy/peers/RemoteSearch.java+++ b/source/net/yacy/peers/RemoteSearch.java@@ -85,7 +85,7 @@ public class RemoteSearch extends Thread {@Overridepublic void run() {- this.event.rankingProcess.oneFeederStarted();+ this.event.oneFeederStarted();try {this.urls = Protocol.primarySearch(this.event,@@ -110,7 +110,7 @@ public class RemoteSearch extends Thread {} catch (final Exception e) {Log.logException(e);} finally {- this.event.rankingProcess.oneFeederTerminated();+ this.event.oneFeederTerminated();}}@@ -218,7 +218,7 @@ public class RemoteSearch extends Thread {Thread secondary = new Thread() {@Overridepublic void run() {- event.rankingProcess.oneFeederStarted();+ event.oneFeederStarted();try {int urls = Protocol.secondarySearch(event,@@ -242,7 +242,7 @@ public class RemoteSearch extends Thread {} catch (final Exception e) {Log.logException(e);} finally {- event.rankingProcess.oneFeederTerminated();+ event.oneFeederTerminated();}}};@@ -268,7 +268,7 @@ public class RemoteSearch extends Thread {while (tmpoffset + tmpcount <= count && tmpcount > 0) {int urls = 0;try {- event.rankingProcess.oneFeederStarted();+ event.oneFeederStarted();urls = Protocol.solrQuery(event,tmpoffset,@@ -288,11 +288,11 @@ public class RemoteSearch extends Thread {} catch (final Exception e) {Log.logException(e);} finally {- event.rankingProcess.oneFeederTerminated();+ event.oneFeederTerminated();}if (urls < tmpcount) break; // there won't be moretmpoffset += tmpcount;- tmpcount = count - tmpoffset; // increase the tmpcount to get to all results in less time+ tmpcount = targetPeer == null ? 10 : count - tmpoffset;}}};diff --git a/source/net/yacy/search/Switchboard.java b/source/net/yacy/search/Switchboard.javaindex 874d25268..7a7a45f23 100644--- a/source/net/yacy/search/Switchboard.java+++ b/source/net/yacy/search/Switchboard.java@@ -3365,7 +3365,7 @@ public final class Switchboard extends serverSwitch {}final Map<DigestURI, String> links;- searchEvent.rankingProcess.oneFeederStarted();+ searchEvent.oneFeederStarted();try {links = Switchboard.this.loader.loadLinks(url, CacheStrategy.NOCACHE, BlacklistType.SEARCH, TextSnippet.snippetMinLoadDelay);if ( links != null ) {@@ -3382,7 +3382,7 @@ public final class Switchboard extends serverSwitch {} catch ( final Throwable e ) {Log.logException(e);} finally {- searchEvent.rankingProcess.oneFeederTerminated();+ searchEvent.oneFeederTerminated();}}}.start();@@ -3466,7 +3466,7 @@ public final class Switchboard extends serverSwitch {// if we have an url then try to load the rssRSSReader rss = null;- searchEvent.rankingProcess.oneFeederStarted();+ searchEvent.oneFeederStarted();try {final Response response =Switchboard.this.loader.load(Switchboard.this.loader.request(url, true, false), CacheStrategy.NOCACHE, BlacklistType.SEARCH, TextSnippet.snippetMinLoadDelay);@@ -3495,7 +3495,7 @@ public final class Switchboard extends serverSwitch {} catch ( final Throwable e ) {//Log.logException(e);} finally {- searchEvent.rankingProcess.oneFeederTerminated();+ searchEvent.oneFeederTerminated();}}}.start();diff --git a/source/net/yacy/search/index/Fulltext.java b/source/net/yacy/search/index/Fulltext.javaindex 0387cdb98..fa0538568 100644--- a/source/net/yacy/search/index/Fulltext.java+++ b/source/net/yacy/search/index/Fulltext.java@@ -42,7 +42,6 @@ import net.yacy.cora.date.GenericFormatter;import net.yacy.cora.date.ISO8601Formatter;import net.yacy.cora.document.ASCII;import net.yacy.cora.document.MultiProtocolURI;-import net.yacy.cora.federate.solr.SchemaConfiguration;import net.yacy.cora.federate.solr.connector.AbstractSolrConnector;import net.yacy.cora.federate.solr.connector.EmbeddedSolrConnector;import net.yacy.cora.federate.solr.connector.RemoteSolrConnector;@@ -362,16 +361,16 @@ public final class Fulltext {byte[] idb = ASCII.getBytes(id);try {if (this.urlIndexFile != null) this.urlIndexFile.remove(idb);- Date sdDate = (Date) connector.getFieldById(id, CollectionSchema.last_modified.getSolrFieldName());- Date docDate = null;- if (sdDate == null || (docDate = SchemaConfiguration.getDate(doc, CollectionSchema.last_modified)) == null || sdDate.before(docDate)) {+ //Date sdDate = (Date) connector.getFieldById(id, CollectionSchema.last_modified.getSolrFieldName());+ //Date docDate = null;+ //if (sdDate == null || (docDate = SchemaConfiguration.getDate(doc, CollectionSchema.last_modified)) == null || sdDate.before(docDate)) {if (this.collectionConfiguration.contains(CollectionSchema.ip_s)) {// ip_s needs a dns lookup which causes blockings during search hereconnector.add(doc);} else synchronized (this.solrInstances) {connector.add(doc);}- }+ //}} catch (SolrException e) {throw new IOException(e.getMessage(), e);}@@ -379,6 +378,12 @@ public final class Fulltext {if (MemoryControl.shortStatus()) clearCache();}+ public void putDocuments(final Collection<SolrInputDocument> docs) throws IOException {+ this.getDefaultConnector().add(docs);+ this.statsDump = null;+ if (MemoryControl.shortStatus()) clearCache();+ }+public void putEdges(final Collection<SolrInputDocument> edges) throws IOException {try {this.getWebgraphConnector().add(edges);@@ -390,21 +395,19 @@ public final class Fulltext {}public void putMetadata(final URIMetadataRow entry) throws IOException {- URIMetadataRow row = entry;-- byte[] idb = row.hash();- String id = ASCII.String(idb);+ byte[] idb = entry.hash();+ //String id = ASCII.String(idb);try {- if (this.urlIndexFile != null) this.urlIndexFile.remove(idb);- SolrDocument sd = this.getDefaultConnector().getById(id);- if (sd == null || (new URIMetadataNode(sd)).isOlder(row)) {+ if (this.urlIndexFile != null) this.urlIndexFile.remove(idb);+ //SolrDocument sd = this.getDefaultConnector().getById(id);+ //if (sd == null || (new URIMetadataNode(sd)).isOlder(entry)) {if (this.collectionConfiguration.contains(CollectionSchema.ip_s)) {// ip_s needs a dns lookup which causes blockings during search here- this.getDefaultConnector().add(getDefaultConfiguration().metadata2solr(row));+ this.getDefaultConnector().add(getDefaultConfiguration().metadata2solr(entry));} else synchronized (this.solrInstances) {- this.getDefaultConnector().add(getDefaultConfiguration().metadata2solr(row));+ this.getDefaultConnector().add(getDefaultConfiguration().metadata2solr(entry));}- }+ //}} catch (SolrException e) {throw new IOException(e.getMessage(), e);}@@ -412,6 +415,20 @@ public final class Fulltext {if (MemoryControl.shortStatus()) clearCache();}+ public void putMetadata(final Collection<URIMetadataRow> entries) throws IOException {+ Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>(entries.size());+ for (URIMetadataRow entry: entries) {+ byte[] idb = entry.hash();+ //String id = ASCII.String(idb);+ if (this.urlIndexFile != null) this.urlIndexFile.remove(idb);+ //SolrDocument sd = this.getDefaultConnector().getById(id, CollectionSchema.last_modified.getSolrFieldName(), CollectionSchema.load_date_dt.getSolrFieldName());+ //if (sd == null || (new URIMetadataNode(sd)).isOlder(entry)) {+ docs.add(getDefaultConfiguration().metadata2solr(entry));+ //}+ }+ putDocuments(docs);+ }+/*** using a fragment of the url hash (6 bytes: bytes 6 to 11) it is possible to address all urls from a specific domain* here such a fragment can be used to delete all these domains at oncediff --git a/source/net/yacy/search/index/Segment.java b/source/net/yacy/search/index/Segment.javaindex 2fd458116..5817dc0a9 100644--- a/source/net/yacy/search/index/Segment.java+++ b/source/net/yacy/search/index/Segment.java@@ -75,7 +75,6 @@ import net.yacy.kelondro.util.MemoryControl;import net.yacy.repository.LoaderDispatcher;import net.yacy.search.Switchboard;import net.yacy.search.SwitchboardConstants;-import net.yacy.search.query.RankingProcess;import net.yacy.search.query.SearchEvent;import net.yacy.search.schema.CollectionConfiguration;import net.yacy.search.schema.CollectionSchema;@@ -216,15 +215,25 @@ public class Segment {return this.termIndex.getBufferSize();}- public int getQueryCount(StringBuilder wordsb) {- return getQueryCount(wordsb.toString());- }-- public int getQueryCount(String word) {+ /**+ * get a guess about the word count. This is only a guess because it uses the term index if present and this index may be+ * influenced by index transmission processes in its statistic word distribution. However, it can be a hint for heuristics+ * which use the word count. Please do NOT use this if the termIndex is not present because it otherwise uses the solr index+ * which makes it painfull slow.+ * @param word+ * @return the number of references for this word.+ */+ public int getWordCountGuess(String word) {if (word == null || word.indexOf(':') >= 0 || word.indexOf(' ') >= 0 || word.indexOf('/') >= 0) return 0;- int count = this.termIndex == null ? 0 : this.termIndex.count(Word.word2hash(word));- try {count += this.fulltext.getDefaultConnector().getQueryCount(CollectionSchema.text_t.getSolrFieldName() + ':' + word);} catch (IOException e) {}- return count;+ if (this.termIndex == null) {+ try {+ return (int) this.fulltext.getDefaultConnector().getQueryCount(CollectionSchema.text_t.getSolrFieldName() + ':' + word);+ } catch (Throwable e) {+ Log.logException(e);+ return 0;+ }+ }+ return this.termIndex.count(Word.word2hash(word));}public boolean exists(final String urlhash) {@@ -511,7 +520,6 @@ public class Segment {// STORE PAGE INDEX INTO WORD INDEX DBint outlinksSame = document.inboundLinks().size();int outlinksOther = document.outboundLinks().size();- final RankingProcess rankingProcess = (searchEvent == null) ? null : searchEvent.rankingProcess;final int urlLength = urlNormalform.length();final int urlComps = MultiProtocolURI.urlComps(url.toString()).length;@@ -555,13 +563,13 @@ public class Segment {try {container = ReferenceContainer.emptyContainer(Segment.wordReferenceFactory, wordhash, 1);container.add(ientry);- rankingProcess.add(container, true, sourceName, -1, 5000);+ searchEvent.addRWIs(container, true, sourceName, -1, 5000);} catch (final SpaceExceededException e) {continue;}}}- if (searchEvent != null) searchEvent.rankingProcess.addFinalize();+ if (searchEvent != null) searchEvent.addFinalize();// assign the catchall wordientry.setWord(wprop == null ? catchallWord : wprop); // we use one of the word properties as template to get the document characteristicsdiff --git a/source/net/yacy/search/query/AccessTracker.java b/source/net/yacy/search/query/AccessTracker.javaindex edd13e8e6..407f965b9 100644--- a/source/net/yacy/search/query/AccessTracker.java+++ b/source/net/yacy/search/query/AccessTracker.java@@ -60,15 +60,15 @@ public class AccessTracker {dumpFile = f;}- public static void add(final Location location, final QueryParams query) {- if (location == Location.local) synchronized (localSearches) {add(localSearches, query);}- if (location == Location.remote) synchronized (remoteSearches) {add(remoteSearches, query);}+ public static void add(final Location location, final QueryParams query, int resultCount) {+ if (location == Location.local) synchronized (localSearches) {add(localSearches, query, resultCount);}+ if (location == Location.remote) synchronized (remoteSearches) {add(remoteSearches, query, resultCount);}}- private static void add(final LinkedList<QueryParams> list, final QueryParams query) {+ private static void add(final LinkedList<QueryParams> list, final QueryParams query, int resultCount) {// learn that this word can be a word completion for the DidYouMeanLibraryString queryString = query.getQueryGoal().getOriginalQueryString(false);- if (query.getResultCount() > 10 && queryString != null && queryString.length() > 0) {+ if (resultCount > 10 && queryString != null && queryString.length() > 0) {final StringBuilder sb = new StringBuilder(queryString);sb.append(queryString);WordCache.learn(sb);@@ -80,7 +80,7 @@ public class AccessTracker {// shrink dump list but keep essentials in dumpwhile (list.size() > maxSize || (!list.isEmpty() && MemoryControl.shortStatus())) {synchronized (list) {- if (!list.isEmpty()) addToDump(list.removeFirst()); else break;+ if (!list.isEmpty()) addToDump(list.removeFirst(), resultCount); else break;}}@@ -92,7 +92,7 @@ public class AccessTracker {while (!list.isEmpty()) {final QueryParams q = list.getFirst();if (q.starttime > timeout) break;- addToDump(list.removeFirst());+ addToDump(list.removeFirst(), resultCount);}}@@ -108,10 +108,10 @@ public class AccessTracker {return 0;}- private static void addToDump(final QueryParams query) {+ private static void addToDump(final QueryParams query, int resultCount) {String queryString = query.getQueryGoal().getOriginalQueryString(false);if (queryString == null || queryString.isEmpty()) return;- addToDump(queryString, Integer.toString(query.getResultCount()), new Date(query.starttime));+ addToDump(queryString, Integer.toString(resultCount), new Date(query.starttime));}public static void addToDump(String querystring, String resultcount) {@@ -138,7 +138,7 @@ public class AccessTracker {public static void dumpLog() {while (!localSearches.isEmpty()) {- addToDump(localSearches.removeFirst());+ addToDump(localSearches.removeFirst(), 0);}Thread t = new Thread() {@Overridediff --git a/source/net/yacy/search/query/QueryParams.java b/source/net/yacy/search/query/QueryParams.javaindex f05cb0372..c2c5d4cee 100644--- a/source/net/yacy/search/query/QueryParams.java+++ b/source/net/yacy/search/query/QueryParams.java@@ -28,15 +28,11 @@ package net.yacy.search.query;import java.util.ArrayList;import java.util.Collection;-import java.util.Collections;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;-import java.util.SortedSet;-import java.util.TreeSet;-import java.util.concurrent.atomic.AtomicInteger;import java.util.regex.Pattern;import java.util.regex.PatternSyntaxException;@@ -56,7 +52,6 @@ import net.yacy.cora.util.SpaceExceededException;import net.yacy.document.Condenser;import net.yacy.document.LibraryProvider;import net.yacy.kelondro.data.meta.DigestURI;-import net.yacy.kelondro.data.meta.URIMetadataRow;import net.yacy.kelondro.data.word.Word;import net.yacy.kelondro.data.word.WordReferenceRow;import net.yacy.kelondro.index.RowHandleSet;@@ -107,7 +102,7 @@ public final class QueryParams {private final int zonecode;public final int maxDistance;public final Bitfield constraint;- final boolean allofconstraint;+ public final boolean allofconstraint;protected CacheStrategy snippetCacheStrategy;public final RankingProfile ranking;private final Segment indexSegment;@@ -128,16 +123,6 @@ public final class QueryParams {public int maxfacets;private SolrQuery cachedQuery;private CollectionConfiguration solrSchema;-- // the following values are filled during the search process as statistics for the search- public final AtomicInteger local_rwi_available; // the number of hits generated/ranked by the local search in rwi index- public final AtomicInteger local_rwi_stored; // the number of existing hits by the local search in rwi index- public final AtomicInteger local_solr_available; // the number of hits generated/ranked by the local search in solr- public final AtomicInteger local_solr_stored; // the number of existing hits by the local search in solr- public final AtomicInteger remote_available; // the number of hits imported from remote peers (rwi/solr mixed)- public final AtomicInteger remote_stored; // the number of existing hits at remote site- public final AtomicInteger remote_peerCount; // the number of peers which contributed to the remote search result- public final SortedSet<byte[]> misses; // url hashes that had been sorted out because of constraints in postrankingpublic QueryParams(final String query_original,@@ -180,14 +165,6 @@ public final class QueryParams {this.lat = 0.0d;this.lon = 0.0d;this.radius = 0.0d;- this.local_rwi_available = new AtomicInteger(0); // the number of results in the local peer after filtering- this.local_rwi_stored = new AtomicInteger(0);- this.local_solr_available= new AtomicInteger(0);- this.local_solr_stored = new AtomicInteger(0);- this.remote_stored = new AtomicInteger(0);- this.remote_available = new AtomicInteger(0); // the number of result contributions from all the remote peers- this.remote_peerCount = new AtomicInteger(0); // the number of remote peers that have contributed- this.misses = Collections.synchronizedSortedSet(new TreeSet<byte[]>(URIMetadataRow.rowdef.objectOrder));this.facetfields = new ArrayList<String>();this.solrSchema = indexSegment.fulltext().getDefaultConfiguration();@@ -289,14 +266,6 @@ public final class QueryParams {this.lat = Math.floor(lat * this.kmNormal) / this.kmNormal;this.lon = Math.floor(lon * this.kmNormal) / this.kmNormal;this.radius = Math.floor(radius * this.kmNormal + 1) / this.kmNormal;- this.local_rwi_available = new AtomicInteger(0); // the number of results in the local peer after filtering- this.local_rwi_stored = new AtomicInteger(0);- this.local_solr_available= new AtomicInteger(0);- this.local_solr_stored = new AtomicInteger(0);- this.remote_stored = new AtomicInteger(0);- this.remote_available = new AtomicInteger(0); // the number of result contributions from all the remote peers- this.remote_peerCount = new AtomicInteger(0); // the number of remote peers that have contributed- this.misses = Collections.synchronizedSortedSet(new TreeSet<byte[]>(URIMetadataRow.rowdef.objectOrder));this.facetfields = new ArrayList<String>();this.solrSchema = indexSegment.fulltext().getDefaultConfiguration();@@ -323,10 +292,6 @@ public final class QueryParams {// the number of result lines that are displayed at once (size of result page)return this.itemsPerPage;}-- public int getResultCount() {- return this.local_rwi_available.get() + this.local_solr_stored.get() - this.misses.size();- }public void setOffset(final int newOffset) {this.offset = newOffset;diff --git a/source/net/yacy/search/query/RankingProcess.java b/source/net/yacy/search/query/RankingProcess.javadeleted file mode 100644index 5f52a8e3f..000000000--- a/source/net/yacy/search/query/RankingProcess.java+++ /dev/null@@ -1,430 +0,0 @@-// RankingProcess.java-// (C) 2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany-// first published 07.11.2007 on http://yacy.net-//-// This is a part of YaCy, a peer-to-peer based web search engine-//-// $LastChangedDate$-// $LastChangedRevision$-// $LastChangedBy$-//-// LICENSE-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--package net.yacy.search.query;--import java.util.HashMap;-import java.util.Iterator;-import java.util.Map;-import java.util.SortedMap;-import java.util.concurrent.BlockingQueue;-import java.util.concurrent.ConcurrentHashMap;-import java.util.concurrent.TimeUnit;-import java.util.concurrent.atomic.AtomicInteger;-import java.util.regex.Pattern;--import net.yacy.cora.document.analysis.Classification.ContentDomain;-import net.yacy.cora.document.MultiProtocolURI;-import net.yacy.cora.document.UTF8;-import net.yacy.cora.federate.yacy.CacheStrategy;-import net.yacy.cora.lod.vocabulary.Tagging;-import net.yacy.cora.sorting.ConcurrentScoreMap;-import net.yacy.cora.sorting.ScoreMap;-import net.yacy.cora.sorting.WeakPriorityBlockingQueue;-import net.yacy.cora.sorting.WeakPriorityBlockingQueue.ReverseElement;-import net.yacy.cora.storage.HandleSet;-import net.yacy.cora.util.SpaceExceededException;-import net.yacy.document.Condenser;-import net.yacy.document.LibraryProvider;-import net.yacy.kelondro.data.meta.URIMetadataRow;-import net.yacy.kelondro.data.word.Word;-import net.yacy.kelondro.data.word.WordReference;-import net.yacy.kelondro.data.word.WordReferenceVars;-import net.yacy.kelondro.index.RowHandleSet;-import net.yacy.kelondro.logging.Log;-import net.yacy.kelondro.rwi.ReferenceContainer;-import net.yacy.kelondro.rwi.TermSearch;-import net.yacy.kelondro.util.Bitfield;-import net.yacy.peers.graphics.ProfilingGraph;-import net.yacy.search.EventTracker;-import net.yacy.search.Switchboard;-import net.yacy.search.index.Segment;-import net.yacy.search.ranking.ReferenceOrder;-import net.yacy.search.snippet.ResultEntry;--public final class RankingProcess extends Thread {-- protected static final int max_results_preparation = 3000, max_results_preparation_special = -1; // -1 means 'no limit'-- //private final SearchEvent searchEvent;- private final QueryParams query;- private SortedMap<byte[], ReferenceContainer<WordReference>> localSearchInclusion;- private final ScoreMap<String> ref; // reference score computation for the commonSense heuristic- private final long maxtime;- protected final WeakPriorityBlockingQueue<WordReferenceVars> rwiStack;- protected final ConcurrentHashMap<String, WeakPriorityBlockingQueue<WordReferenceVars>> doubleDomCache; // key = domhash (6 bytes); value = like stack- private final int[] flagcount; // flag counter- private final AtomicInteger feedersAlive, feedersTerminated;- private boolean addRunning;- protected final AtomicInteger receivedRemoteReferences;- protected final ReferenceOrder order;- protected final HandleSet urlhashes; // map for double-check; String/Long relation, addresses ranking number (backreference for deletion)- private final Map<String, String> taggingPredicates; // a map from tagging vocabulary names to tagging predicate uris- private boolean remote;-- protected RankingProcess(final QueryParams query, boolean remote) {- // we collect the urlhashes and construct a list with urlEntry objects- // attention: if minEntries is too high, this method will not terminate within the maxTime- // sortorder: 0 = hash, 1 = url, 2 = ranking- this.query = query;- this.remote = remote;- this.localSearchInclusion = null;- this.ref = new ConcurrentScoreMap<String>();- this.maxtime = query.maxtime;- int stackMaxsize = query.snippetCacheStrategy == null || query.snippetCacheStrategy == CacheStrategy.CACHEONLY ? max_results_preparation_special : max_results_preparation;- this.rwiStack = new WeakPriorityBlockingQueue<WordReferenceVars>(stackMaxsize, false);- this.doubleDomCache = new ConcurrentHashMap<String, WeakPriorityBlockingQueue<WordReferenceVars>>();- this.flagcount = new int[32];- for ( int i = 0; i < 32; i++ ) {- this.flagcount[i] = 0;- }- this.feedersAlive = new AtomicInteger(0);- this.feedersTerminated = new AtomicInteger(0);- this.addRunning = true;- this.receivedRemoteReferences = new AtomicInteger(0);- this.order = new ReferenceOrder(this.query.ranking, UTF8.getBytes(this.query.targetlang));- this.urlhashes = new RowHandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, 100);- this.taggingPredicates = new HashMap<String, String>();- for (Tagging t: LibraryProvider.autotagging.getVocabularies()) {- this.taggingPredicates.put(t.getName(), t.getPredicate());- }- }-- public ReferenceOrder getOrder() {- return this.order;- }-- protected boolean feedingIsFinished() {- return- this.feedersTerminated.intValue() > (this.remote ? 1 : 0) &&- this.feedersAlive.get() == 0;// &&- //(!this.remote || this.remote_indexCount > 0);- }-- /**- * method to signal the incoming stack that one feeder has terminated- */- public void oneFeederTerminated() {- this.feedersTerminated.incrementAndGet();- final int c = this.feedersAlive.decrementAndGet();- assert c >= 0 : "feeders = " + c;- }-- public void oneFeederStarted() {- this.feedersAlive.addAndGet(1);- }-- public QueryParams getQuery() {- return this.query;- }-- public int[] flagCount() {- return this.flagcount;- }-- protected void addBegin() {- this.addRunning = true;- }-- public void addFinalize() {- this.addRunning = false;- }-- protected boolean addRunning() {- return this.addRunning;- }-- public boolean rwiIsEmpty() {- if ( !this.rwiStack.isEmpty() ) {- return false;- }- for ( final WeakPriorityBlockingQueue<WordReferenceVars> s : this.doubleDomCache.values() ) {- if ( !s.isEmpty() ) {- return false;- }- }- return true;- }-- protected int rwiQueueSize() {- int c = this.rwiStack.sizeQueue();- for ( final WeakPriorityBlockingQueue<WordReferenceVars> s : this.doubleDomCache.values() ) {- c += s.sizeQueue();- }- return c;- }-- protected boolean testFlags(final Bitfield flags) {- if (this.query.constraint == null) return true;- // test if ientry matches with filter- // if all = true: let only entries pass that has all matching bits- // if all = false: let all entries pass that has at least one matching bit- if (this.query.allofconstraint) {- for ( int i = 0; i < 32; i++ ) {- if ((this.query.constraint.get(i)) && (!flags.get(i))) return false;- }- return true;- }- for (int i = 0; i < 32; i++) {- if ((this.query.constraint.get(i)) && (flags.get(i))) return true;- }- return false;- }-- @Override- public void run() {-- if (query.getSegment().termIndex() == null) return; // nothing to do; this index is not used-- // do a search- oneFeederStarted();-- // sort the local containers and truncate it to a limited count,- // so following sortings together with the global results will be fast- try {- final long timer = System.currentTimeMillis();- final TermSearch<WordReference> search =- this.query- .getSegment()- .termIndex()- .query(- this.query.getQueryGoal().getIncludeHashes(),- this.query.getQueryGoal().getExcludeHashes(),- null,- Segment.wordReferenceFactory,- this.query.maxDistance);- this.localSearchInclusion = search.inclusion();- final ReferenceContainer<WordReference> index = search.joined();- EventTracker.update(- EventTracker.EClass.SEARCH,- new ProfilingGraph.EventSearch(- this.query.id(true),- SearchEventType.JOIN,- this.query.getQueryGoal().getOriginalQueryString(false),- index.size(),- System.currentTimeMillis() - timer),- false);- if ( !index.isEmpty() ) {- add(index, true, "local index: " + this.query.getSegment().getLocation(), -1, this.maxtime);- this.addFinalize();- }- } catch ( final Exception e ) {- Log.logException(e);- } finally {- oneFeederTerminated();- }- }-- public void add(- final ReferenceContainer<WordReference> index,- final boolean local,- final String resourceName,- final int fullResource,- final long maxtime) {- // we collect the urlhashes and construct a list with urlEntry objects- // attention: if minEntries is too high, this method will not terminate within the maxTime- //Log.logInfo("RWIProcess", "added a container, size = " + index.size());-- this.addRunning = true;- assert (index != null);- if (index.isEmpty()) return;- if (local) {- this.query.local_rwi_stored.addAndGet(fullResource);- } else {- assert fullResource >= 0 : "fullResource = " + fullResource;- this.query.remote_stored.addAndGet(fullResource);- this.query.remote_peerCount.incrementAndGet();- }- long timer = System.currentTimeMillis();-- // normalize entries- final BlockingQueue<WordReferenceVars> decodedEntries = this.order.normalizeWith(index, maxtime);- int is = index.size();- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(- this.query.id(true),- SearchEventType.NORMALIZING,- resourceName,- is,- System.currentTimeMillis() - timer), false);- if (!local) this.receivedRemoteReferences.addAndGet(is);-- // iterate over normalized entries and select some that are better than currently stored- timer = System.currentTimeMillis();-- // apply all constraints- long timeout = System.currentTimeMillis() + maxtime;- try {- WordReferenceVars iEntry;- long remaining;- pollloop: while ( true ) {- remaining = timeout - System.currentTimeMillis();- if (remaining <= 0) {- Log.logWarning("RWIProcess", "terminated 'add' loop before poll time-out = " + remaining + ", decodedEntries.size = " + decodedEntries.size());- break;- }- iEntry = decodedEntries.poll(remaining, TimeUnit.MILLISECONDS);- if (iEntry == null) {- Log.logWarning("RWIProcess", "terminated 'add' loop after poll time-out = " + remaining + ", decodedEntries.size = " + decodedEntries.size());- break pollloop;- }- if (iEntry == WordReferenceVars.poison) {- break pollloop;- }- assert (iEntry.urlhash().length == index.row().primaryKeyLength);-- // doublecheck for urls- if (this.urlhashes.has(iEntry.urlhash())) continue pollloop;-- // increase flag counts- Bitfield flags = iEntry.flags();- for (int j = 0; j < 32; j++) {- if (flags.get(j)) this.flagcount[j]++;- }-- // check constraints- if (!this.testFlags(flags)) continue pollloop;-- // check document domain- if (this.query.contentdom.getCode() > 0 &&- ((this.query.contentdom == ContentDomain.AUDIO && !(flags.get(Condenser.flag_cat_hasaudio))) ||- (this.query.contentdom == ContentDomain.VIDEO && !(flags.get(Condenser.flag_cat_hasvideo))) ||- (this.query.contentdom == ContentDomain.IMAGE && !(flags.get(Condenser.flag_cat_hasimage))) ||- (this.query.contentdom == ContentDomain.APP && !(flags.get(Condenser.flag_cat_hasapp))))) {- continue pollloop;- }-- // count domZones- //this.domZones[DigestURI.domDomain(iEntry.metadataHash())]++;-- // check site constraints- final String hosthash = iEntry.hosthash();- if ( this.query.modifier.sitehash == null ) {- if (this.query.siteexcludes != null && this.query.siteexcludes.contains(hosthash)) continue pollloop;- } else {- // filter out all domains that do not match with the site constraint- if (!hosthash.equals(this.query.modifier.sitehash)) continue pollloop;- }-- // finally extend the double-check and insert result to stack- this.urlhashes.putUnique(iEntry.urlhash());- rankingtryloop: while (true) {- try {- this.rwiStack.put(new ReverseElement<WordReferenceVars>(iEntry, this.order.cardinal(iEntry))); // inserts the element and removes the worst (which is smallest)- break rankingtryloop;- } catch ( final ArithmeticException e ) {- // this may happen if the concurrent normalizer changes values during cardinal computation- continue rankingtryloop;- }- }- // increase counter for statistics- if (local) this.query.local_rwi_available.incrementAndGet(); else this.query.remote_available.incrementAndGet();- }- if (System.currentTimeMillis() >= timeout) Log.logWarning("RWIProcess", "rwi normalization ended with timeout = " + maxtime);-- } catch ( final InterruptedException e ) {- } catch ( final SpaceExceededException e ) {- }-- //if ((query.neededResults() > 0) && (container.size() > query.neededResults())) remove(true, true);- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(- this.query.id(true),- SearchEventType.PRESORT,- resourceName,- index.size(),- System.currentTimeMillis() - timer), false);- }-- protected Map<byte[], ReferenceContainer<WordReference>> searchContainerMap() {- // direct access to the result maps is needed for abstract generation- // this is only available if execQuery() was called before- return this.localSearchInclusion;- }-- public ScoreMap<String> getTopics(final int maxcount, final long maxtime) {- // create a list of words that had been computed by statistics over all- // words that appeared in the url or the description of all urls- final ScoreMap<String> result = new ConcurrentScoreMap<String>();- if ( this.ref.sizeSmaller(2) ) {- this.ref.clear(); // navigators with one entry are not useful- }- final Map<String, Float> counts = new HashMap<String, Float>();- final Iterator<String> i = this.ref.keys(false);- String word;- int c;- float q, min = Float.MAX_VALUE, max = Float.MIN_VALUE;- int ic = maxcount;- long timeout = System.currentTimeMillis() + maxtime;- while ( ic-- > 0 && i.hasNext() ) {- word = i.next();- if ( word == null ) {- continue;- }- c = this.query.getSegment().getQueryCount(word);- if ( c > 0 ) {- q = ((float) this.ref.get(word)) / ((float) c);- min = Math.min(min, q);- max = Math.max(max, q);- counts.put(word, q);- }- if (System.currentTimeMillis() > timeout) break;- }- if ( max > min ) {- for ( final Map.Entry<String, Float> ce : counts.entrySet() ) {- result.set(ce.getKey(), (int) (((double) maxcount) * (ce.getValue() - min) / (max - min)));- }- }- return this.ref;- }-- private final static Pattern lettermatch = Pattern.compile("[a-z]+");-- public void addTopic(final String[] words) {- String word;- for ( final String w : words ) {- word = w.toLowerCase();- if ( word.length() > 2- && "http_html_php_ftp_www_com_org_net_gov_edu_index_home_page_for_usage_the_and_zum_der_die_das_und_the_zur_bzw_mit_blog_wiki_aus_bei_off"- .indexOf(word) < 0- && !this.query.getQueryGoal().getIncludeHashes().has(Word.word2hash(word))- && lettermatch.matcher(word).matches()- && !Switchboard.badwords.contains(word)- && !Switchboard.stopwords.contains(word) ) {- this.ref.inc(word);- }- }- }-- protected void addTopics(final ResultEntry resultEntry) {- // take out relevant information for reference computation- if ((resultEntry.url() == null) || (resultEntry.title() == null)) return;- final String[] descrcomps = MultiProtocolURI.splitpattern.split(resultEntry.title().toLowerCase()); // words in the description-- // add references- addTopic(descrcomps);- }---}diff --git a/source/net/yacy/search/query/SearchEvent.java b/source/net/yacy/search/query/SearchEvent.javaindex e370448a6..8ca053a86 100644--- a/source/net/yacy/search/query/SearchEvent.java+++ b/source/net/yacy/search/query/SearchEvent.java@@ -28,18 +28,27 @@ package net.yacy.search.query;import java.text.ParseException;import java.util.ArrayList;+import java.util.Collections;import java.util.ConcurrentModificationException;+import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.SortedMap;+import java.util.SortedSet;import java.util.TreeMap;+import java.util.TreeSet;+import java.util.concurrent.BlockingQueue;import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;+import java.util.regex.Pattern;import net.yacy.contentcontrol.ContentControlFilterUpdateThread;import net.yacy.cora.date.GenericFormatter;import net.yacy.cora.document.ASCII;+import net.yacy.cora.document.MultiProtocolURI;+import net.yacy.cora.document.UTF8;import net.yacy.cora.document.analysis.Classification;import net.yacy.cora.document.analysis.Classification.ContentDomain;import net.yacy.cora.federate.yacy.CacheStrategy;@@ -61,12 +70,15 @@ import net.yacy.document.LargeNumberCache;import net.yacy.document.LibraryProvider;import net.yacy.document.TextParser;import net.yacy.kelondro.data.meta.URIMetadataNode;+import net.yacy.kelondro.data.meta.URIMetadataRow;+import net.yacy.kelondro.data.word.Word;import net.yacy.kelondro.data.word.WordReference;import net.yacy.kelondro.data.word.WordReferenceFactory;import net.yacy.kelondro.data.word.WordReferenceVars;import net.yacy.kelondro.index.RowHandleSet;import net.yacy.kelondro.logging.Log;import net.yacy.kelondro.rwi.ReferenceContainer;+import net.yacy.kelondro.rwi.TermSearch;import net.yacy.kelondro.util.Bitfield;import net.yacy.kelondro.util.MemoryControl;import net.yacy.peers.RemoteSearch;@@ -77,11 +89,17 @@ import net.yacy.repository.LoaderDispatcher;import net.yacy.repository.Blacklist.BlacklistType;import net.yacy.search.EventTracker;import net.yacy.search.Switchboard;+import net.yacy.search.index.Segment;+import net.yacy.search.ranking.ReferenceOrder;import net.yacy.search.schema.CollectionSchema;import net.yacy.search.snippet.ResultEntry;+import net.yacy.search.snippet.TextSnippet;+import net.yacy.search.snippet.TextSnippet.ResultClass;public final class SearchEvent {+ private static final int max_results_preparation = 3000, max_results_preparation_special = -1; // -1 means 'no limit'+private static long noRobinsonLocalRWISearch = 0;static {try {@@ -92,26 +110,23 @@ public final class SearchEvent {public static Log log = new Log("SEARCH");- private static final long maxWaitPerResult = 30;public static final int SNIPPET_MAX_LENGTH = 220;- private final static int SNIPPET_WORKER_THREADS = Math.max(4, Runtime.getRuntime().availableProcessors() * 2);private static final int MAX_TOPWORDS = 12; // default count of words for topicnavigagtorprivate long eventTime;public QueryParams query;public final SeedDB peers;final WorkTables workTables;- public final RankingProcess rankingProcess; // ordered search results, grows dynamically as all the query threads enrich this containerpublic final SecondarySearchSuperviser secondarySearchSuperviser;public final List<RemoteSearch> primarySearchThreadsL;- protected Thread[] secondarySearchThreads;+ public Thread[] secondarySearchThreads;public final SortedMap<byte[], String> preselectedPeerHashes;private final Thread localSearchThread;private final SortedMap<byte[], Integer> IACount;private final SortedMap<byte[], String> IAResults;private final SortedMap<byte[], HeuristicResult> heuristics;private byte[] IAmaxcounthash, IAneardhthash;- private final Thread localsearch;+ public Thread rwiProcess, localsearch;private final AtomicInteger expectedRemoteReferences, maxExpectedRemoteReferences; // counter for referenced that had been sorted out for other reasonspublic final ScoreMap<String> hostNavigator; // a counter for the appearance of host namespublic final ScoreMap<String> authorNavigator; // a counter for the appearances of authors@@ -120,18 +135,42 @@ public final class SearchEvent {public final ScoreMap<String> filetypeNavigator; // a counter for file typespublic final Map<String, ScoreMap<String>> vocabularyNavigator; // counters for Vocabularies; key is metatag.getVocabularyName()private final int topicNavigatorCount; // if 0 no topicNavigator, holds expected number of terms for the topicNavigator- protected final WeakPriorityBlockingQueue<URIMetadataNode> nodeStack;- protected final WeakPriorityBlockingQueue<ResultEntry> result;- protected final LoaderDispatcher loader;- protected final HandleSet snippetFetchWordHashes; // a set of word hashes that are used to match with the snippets- protected final boolean deleteIfSnippetFail;- private SnippetWorker[] workerThreads;+ private final LoaderDispatcher loader;+ private final HandleSet snippetFetchWordHashes; // a set of word hashes that are used to match with the snippets+ private final boolean deleteIfSnippetFail;private long urlRetrievalAllTime;- protected long snippetComputationAllTime;- protected ConcurrentHashMap<String, String> snippets;+ private long snippetComputationAllTime;+ private ConcurrentHashMap<String, String> snippets;private final boolean remote;- private boolean cleanupState;-+ private SortedMap<byte[], ReferenceContainer<WordReference>> localSearchInclusion;+ private final ScoreMap<String> ref; // reference score computation for the commonSense heuristic+ private final long maxtime;+ private final ConcurrentHashMap<String, WeakPriorityBlockingQueue<WordReferenceVars>> doubleDomCache; // key = domhash (6 bytes); value = like stack+ private final int[] flagcount; // flag counter+ private final AtomicInteger feedersAlive, feedersTerminated;+ private boolean addRunning;+ private final AtomicInteger receivedRemoteReferences;+ private final ReferenceOrder order;+ private final HandleSet urlhashes; // map for double-check; String/Long relation, addresses ranking number (backreference for deletion)+ private final Map<String, String> taggingPredicates; // a map from tagging vocabulary names to tagging predicate uris+ private final WeakPriorityBlockingQueue<WordReferenceVars> rwiStack; // thats the bag where the RWI search process writes to+ private final WeakPriorityBlockingQueue<URIMetadataNode> nodeStack; // thats the bag where the solr results are written to+ private final WeakPriorityBlockingQueue<ResultEntry> resultList; // thats the result list where the actual search result is waiting to be displayed++ // the following values are filled during the search process as statistics for the search+ public final AtomicInteger local_rwi_available; // the number of hits generated/ranked by the local search in rwi index+ public final AtomicInteger local_rwi_stored; // the number of existing hits by the local search in rwi index+ public final AtomicInteger local_solr_available; // the number of hits generated/ranked by the local search in solr+ public final AtomicInteger local_solr_stored; // the number of existing hits by the local search in solr+ public final AtomicInteger remote_available; // the number of hits imported from remote peers (rwi/solr mixed)+ public final AtomicInteger remote_stored; // the number of existing hits at remote site+ public final AtomicInteger remote_peerCount; // the number of peers which contributed to the remote search result+ public final SortedSet<byte[]> misses; // url hashes that had been sorted out because of constraints in postranking++ public int getResultCount() {+ return this.rwiStack.sizeQueue() + this.nodeStack.sizeQueue() + this.resultList.sizeAvailable();+ }+protected SearchEvent(final QueryParams query,final SeedDB peers,@@ -144,6 +183,7 @@ public final class SearchEvent {final int burstRobinsonPercent,final int burstMultiwordPercent,final boolean deleteIfSnippetFail) {+if (MemoryControl.available() < 1024 * 1024 * 100) SearchEventCache.cleanupEvents(false);this.eventTime = System.currentTimeMillis(); // for lifetime checkthis.peers = peers;@@ -151,50 +191,20 @@ public final class SearchEvent {this.query = query;this.loader = loader;this.nodeStack = new WeakPriorityBlockingQueue<URIMetadataNode>(300, false);-this.maxExpectedRemoteReferences = new AtomicInteger(0);this.expectedRemoteReferences = new AtomicInteger(0);// prepare configured search navigationfinal String navcfg = Switchboard.getSwitchboard().getConfig("search.navigation", "");- if (navcfg.contains("authors")) {- this.authorNavigator = new ConcurrentScoreMap<String>();- } else {- this.authorNavigator = null;- }- if (navcfg.contains("namespace")) {- this.namespaceNavigator = new ConcurrentScoreMap<String>();- } else {- this.namespaceNavigator = null;- }- if (navcfg.contains("hosts")) {- this.hostNavigator = new ConcurrentScoreMap<String>();- } else {- this.hostNavigator = null;- }- if (navcfg.contains("protocol")) {- this.protocolNavigator = new ConcurrentScoreMap<String>();- } else {- this.protocolNavigator = null;- }- if (navcfg.contains("filetype")) {- this.filetypeNavigator = new ConcurrentScoreMap<String>();- } else {- this.filetypeNavigator = null;- }- if (navcfg.contains("topics")) {- topicNavigatorCount = MAX_TOPWORDS;- } else- topicNavigatorCount = 0;-+ this.authorNavigator = navcfg.contains("authors") ? new ConcurrentScoreMap<String>() : null;+ this.namespaceNavigator = navcfg.contains("namespace") ? new ConcurrentScoreMap<String>() : null;+ this.hostNavigator = navcfg.contains("hosts") ? new ConcurrentScoreMap<String>() : null;+ this.protocolNavigator = navcfg.contains("protocol") ? new ConcurrentScoreMap<String>() : null;+ this.filetypeNavigator = navcfg.contains("filetype") ? new ConcurrentScoreMap<String>() : null;+ this.topicNavigatorCount = navcfg.contains("topics") ? MAX_TOPWORDS : 0;this.vocabularyNavigator = new ConcurrentHashMap<String, ScoreMap<String>>();-- this.snippets = new ConcurrentHashMap<String, String>();-- this.secondarySearchSuperviser =- (this.query.getQueryGoal().getIncludeHashes().size() > 1) ? new SecondarySearchSuperviser(this) : null; // generate abstracts only for combined searches- if ( this.secondarySearchSuperviser != null ) {- this.secondarySearchSuperviser.start();- }+ this.snippets = new ConcurrentHashMap<String, String>();+ this.secondarySearchSuperviser = (this.query.getQueryGoal().getIncludeHashes().size() > 1) ? new SecondarySearchSuperviser(this) : null; // generate abstracts only for combined searches+ if (this.secondarySearchSuperviser != null) this.secondarySearchSuperviser.start();this.secondarySearchThreads = null;this.preselectedPeerHashes = preselectedPeerHashes;this.IAResults = new TreeMap<byte[], String>(Base64Order.enhancedCoder);@@ -203,28 +213,53 @@ public final class SearchEvent {this.IAmaxcounthash = null;this.IAneardhthash = null;this.localSearchThread = null;- this.remote =- (peers != null && peers.sizeConnected() > 0)- && (this.query.domType == QueryParams.Searchdom.CLUSTER || (this.query.domType == QueryParams.Searchdom.GLOBAL && peers- .mySeed()- .getFlagAcceptRemoteIndex()));+ this.remote = (peers != null && peers.sizeConnected() > 0) && (this.query.domType == QueryParams.Searchdom.CLUSTER || (this.query.domType == QueryParams.Searchdom.GLOBAL && peers.mySeed().getFlagAcceptRemoteIndex()));+ this.local_rwi_available = new AtomicInteger(0); // the number of results in the local peer after filtering+ this.local_rwi_stored = new AtomicInteger(0);+ this.local_solr_available= new AtomicInteger(0);+ this.local_solr_stored = new AtomicInteger(0);+ this.remote_stored = new AtomicInteger(0);+ this.remote_available = new AtomicInteger(0); // the number of result contributions from all the remote peers+ this.remote_peerCount = new AtomicInteger(0); // the number of remote peers that have contributed+ this.misses = Collections.synchronizedSortedSet(new TreeSet<byte[]>(URIMetadataRow.rowdef.objectOrder));final long start = System.currentTimeMillis();// do a soft commit for fresh results- query.getSegment().fulltext().commit(true);+ //query.getSegment().fulltext().commit(true);- // prepare a local RWI search- // initialize a ranking process that is the target for data- // that is generated concurrently from local and global search threads- this.rankingProcess = new RankingProcess(this.query, remote);+ // we collect the urlhashes and construct a list with urlEntry objects+ // attention: if minEntries is too high, this method will not terminate within the maxTime+ // sortorder: 0 = hash, 1 = url, 2 = ranking+ this.localSearchInclusion = null;+ this.ref = new ConcurrentScoreMap<String>();+ this.maxtime = query.maxtime;+ int stackMaxsize = query.snippetCacheStrategy == null || query.snippetCacheStrategy == CacheStrategy.CACHEONLY ? max_results_preparation_special : max_results_preparation;+ this.rwiStack = new WeakPriorityBlockingQueue<WordReferenceVars>(stackMaxsize, false);+ this.doubleDomCache = new ConcurrentHashMap<String, WeakPriorityBlockingQueue<WordReferenceVars>>();+ this.flagcount = new int[32];+ for ( int i = 0; i < 32; i++ ) {+ this.flagcount[i] = 0;+ }+ this.feedersAlive = new AtomicInteger(0);+ this.feedersTerminated = new AtomicInteger(0);+ this.addRunning = true;+ this.receivedRemoteReferences = new AtomicInteger(0);+ this.order = new ReferenceOrder(this.query.ranking, UTF8.getBytes(this.query.targetlang));+ this.urlhashes = new RowHandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, 100);+ this.taggingPredicates = new HashMap<String, String>();+ for (Tagging t: LibraryProvider.autotagging.getVocabularies()) {+ this.taggingPredicates.put(t.getName(), t.getPredicate());+ }// start a local solr searchthis.localsearch = RemoteSearch.solrRemoteSearch(this, 100, null /*this peer*/, Switchboard.urlBlacklist);// start a local RWI search concurrently- if (this.remote || this.peers.mySeed().getBirthdate() < noRobinsonLocalRWISearch) {+ this.rwiProcess = null;+ if (query.getSegment().connectedRWI() && (!this.remote || this.peers.mySeed().getBirthdate() < noRobinsonLocalRWISearch)) {// we start the local search only if this peer is doing a remote search or when it is doing a local search and the peer is old- if (query.getSegment().connectedRWI()) this.rankingProcess.start();+ rwiProcess = new RWIProcess();+ rwiProcess.start();}if (this.remote) {@@ -270,7 +305,7 @@ public final class SearchEvent {if ( generateAbstracts ) {// we need the results nowtry {- if (query.getSegment().connectedRWI()) this.rankingProcess.join();+ if (rwiProcess != null && query.getSegment().connectedRWI()) rwiProcess.join();} catch ( final Throwable e ) {}// compute index abstracts@@ -278,9 +313,9 @@ public final class SearchEvent {int maxcount = -1;long mindhtdistance = Long.MAX_VALUE, l;byte[] wordhash;- assert !query.getSegment().connectedRWI() || this.rankingProcess.searchContainerMap() != null;- if (this.rankingProcess.searchContainerMap() != null) {- for (final Map.Entry<byte[], ReferenceContainer<WordReference>> entry : this.rankingProcess.searchContainerMap().entrySet()) {+ assert !query.getSegment().connectedRWI() || this.searchContainerMap() != null;+ if (this.searchContainerMap() != null) {+ for (final Map.Entry<byte[], ReferenceContainer<WordReference>> entry : this.searchContainerMap().entrySet()) {wordhash = entry.getKey();final ReferenceContainer<WordReference> container = entry.getValue();assert (Base64Order.enhancedCoder.equal(container.getTermHash(), wordhash)) : "container.getTermHash() = " + ASCII.String(container.getTermHash()) + ", wordhash = " + ASCII.String(wordhash);@@ -298,12 +333,12 @@ public final class SearchEvent {this.IAResults.put(wordhash, WordReferenceFactory.compressIndex(container, null, 1000).toString());}}- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEventType.ABSTRACTS, "", this.rankingProcess.searchContainerMap() == null ? 0 : this.rankingProcess.searchContainerMap().size(), System.currentTimeMillis() - timer), false);+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEventType.ABSTRACTS, "", this.searchContainerMap() == null ? 0 : this.searchContainerMap().size(), System.currentTimeMillis() - timer), false);} else {// give process time to accumulate a certain amount of data// before a reading process wants to get results from ittry {- if (query.getSegment().connectedRWI()) this.rankingProcess.join(100);+ if (rwiProcess != null && query.getSegment().connectedRWI()) rwiProcess.join(100);} catch ( final Throwable e ) {}// this will reduce the maximum waiting time until results are available to 100 milliseconds@@ -313,10 +348,9 @@ public final class SearchEvent {// start worker threads to fetch urls and snippetsthis.deleteIfSnippetFail = deleteIfSnippetFail;- this.cleanupState = false;this.urlRetrievalAllTime = 0;this.snippetComputationAllTime = 0;- this.result = new WeakPriorityBlockingQueue<ResultEntry>(Math.max(1000, 10 * query.itemsPerPage()), true); // this is the result, enriched with snippets, ranked and ordered by ranking+ this.resultList = new WeakPriorityBlockingQueue<ResultEntry>(Math.max(1000, 10 * query.itemsPerPage()), true); // this is the result, enriched with snippets, ranked and ordered by ranking// snippets do not need to match with the complete query hashes,// only with the query minus the stopwords which had not been used for the search@@ -332,11 +366,6 @@ public final class SearchEvent {this.snippetFetchWordHashes.excludeDestructive(Switchboard.stopwordHashes);}- // start worker threads to fetch urls and snippets- this.workerThreads = null;- deployWorker(Math.min(SNIPPET_WORKER_THREADS, query.itemsPerPage), query.neededResults());- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(query.id(true), SearchEventType.SNIPPETFETCH_START, ((this.workerThreads == null) ? "no" : this.workerThreads.length) + " online snippet fetch threads started", 0, 0), false);-// clean up eventsSearchEventCache.cleanupEvents(false);EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEventType.CLEANUP, "", 0, 0), false);@@ -347,6 +376,176 @@ public final class SearchEvent {}SearchEventCache.put(this.query.id(false), this);}++ private class RWIProcess extends Thread {++ public RWIProcess() {+ super();+ }++ @Override+ public void run() {++ if (query.getSegment().termIndex() == null) return; // nothing to do; this index is not used++ // do a search+ oneFeederStarted();++ // sort the local containers and truncate it to a limited count,+ // so following sortings together with the global results will be fast+ try {+ final long timer = System.currentTimeMillis();+ final TermSearch<WordReference> search =+ SearchEvent.this.query+ .getSegment()+ .termIndex()+ .query(+ SearchEvent.this.query.getQueryGoal().getIncludeHashes(),+ SearchEvent.this.query.getQueryGoal().getExcludeHashes(),+ null,+ Segment.wordReferenceFactory,+ SearchEvent.this.query.maxDistance);+ SearchEvent.this.localSearchInclusion = search.inclusion();+ final ReferenceContainer<WordReference> index = search.joined();+ EventTracker.update(+ EventTracker.EClass.SEARCH,+ new ProfilingGraph.EventSearch(+ SearchEvent.this.query.id(true),+ SearchEventType.JOIN,+ SearchEvent.this.query.getQueryGoal().getOriginalQueryString(false),+ index.size(),+ System.currentTimeMillis() - timer),+ false);+ if ( !index.isEmpty() ) {+ addRWIs(index, true, "local index: " + SearchEvent.this.query.getSegment().getLocation(), -1, SearchEvent.this.maxtime);+ SearchEvent.this.addFinalize();+ }+ } catch ( final Exception e ) {+ Log.logException(e);+ } finally {+ oneFeederTerminated();+ }+ }+ }++ public void addRWIs(+ final ReferenceContainer<WordReference> index,+ final boolean local,+ final String resourceName,+ final int fullResource,+ final long maxtime) {+ // we collect the urlhashes and construct a list with urlEntry objects+ // attention: if minEntries is too high, this method will not terminate within the maxTime+ //Log.logInfo("SearchEvent", "added a container, size = " + index.size());++ this.addRunning = true;+ assert (index != null);+ if (index.isEmpty()) return;+ if (local) {+ this.local_rwi_stored.addAndGet(fullResource);+ } else {+ assert fullResource >= 0 : "fullResource = " + fullResource;+ this.remote_stored.addAndGet(fullResource);+ this.remote_peerCount.incrementAndGet();+ }+ long timer = System.currentTimeMillis();++ // normalize entries+ final BlockingQueue<WordReferenceVars> decodedEntries = this.order.normalizeWith(index, maxtime);+ int is = index.size();+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(+ this.query.id(true),+ SearchEventType.NORMALIZING,+ resourceName,+ is,+ System.currentTimeMillis() - timer), false);+ if (!local) this.receivedRemoteReferences.addAndGet(is);++ // iterate over normalized entries and select some that are better than currently stored+ timer = System.currentTimeMillis();++ // apply all constraints+ long timeout = System.currentTimeMillis() + maxtime;+ try {+ WordReferenceVars iEntry;+ long remaining;+ pollloop: while ( true ) {+ remaining = timeout - System.currentTimeMillis();+ if (remaining <= 0) {+ Log.logWarning("SearchEvent", "terminated 'add' loop before poll time-out = " + remaining + ", decodedEntries.size = " + decodedEntries.size());+ break;+ }+ iEntry = decodedEntries.poll(remaining, TimeUnit.MILLISECONDS);+ if (iEntry == null) {+ Log.logWarning("SearchEvent", "terminated 'add' loop after poll time-out = " + remaining + ", decodedEntries.size = " + decodedEntries.size());+ break pollloop;+ }+ if (iEntry == WordReferenceVars.poison) {+ break pollloop;+ }+ assert (iEntry.urlhash().length == index.row().primaryKeyLength);++ // doublecheck for urls+ if (this.urlhashes.has(iEntry.urlhash())) continue pollloop;++ // increase flag counts+ Bitfield flags = iEntry.flags();+ for (int j = 0; j < 32; j++) {+ if (flags.get(j)) this.flagcount[j]++;+ }++ // check constraints+ if (!this.testFlags(flags)) continue pollloop;++ // check document domain+ if (this.query.contentdom.getCode() > 0 &&+ ((this.query.contentdom == ContentDomain.AUDIO && !(flags.get(Condenser.flag_cat_hasaudio))) ||+ (this.query.contentdom == ContentDomain.VIDEO && !(flags.get(Condenser.flag_cat_hasvideo))) ||+ (this.query.contentdom == ContentDomain.IMAGE && !(flags.get(Condenser.flag_cat_hasimage))) ||+ (this.query.contentdom == ContentDomain.APP && !(flags.get(Condenser.flag_cat_hasapp))))) {+ continue pollloop;+ }++ // count domZones+ //this.domZones[DigestURI.domDomain(iEntry.metadataHash())]++;++ // check site constraints+ final String hosthash = iEntry.hosthash();+ if ( this.query.modifier.sitehash == null ) {+ if (this.query.siteexcludes != null && this.query.siteexcludes.contains(hosthash)) continue pollloop;+ } else {+ // filter out all domains that do not match with the site constraint+ if (!hosthash.equals(this.query.modifier.sitehash)) continue pollloop;+ }++ // finally extend the double-check and insert result to stack+ this.urlhashes.putUnique(iEntry.urlhash());+ rankingtryloop: while (true) {+ try {+ this.rwiStack.put(new ReverseElement<WordReferenceVars>(iEntry, this.order.cardinal(iEntry))); // inserts the element and removes the worst (which is smallest)+ break rankingtryloop;+ } catch ( final ArithmeticException e ) {+ // this may happen if the concurrent normalizer changes values during cardinal computation+ continue rankingtryloop;+ }+ }+ // increase counter for statistics+ if (local) this.local_rwi_available.incrementAndGet(); else this.remote_available.incrementAndGet();+ }+ if (System.currentTimeMillis() >= timeout) Log.logWarning("SearchEvent", "rwi normalization ended with timeout = " + maxtime);++ } catch ( final InterruptedException e ) {+ } catch ( final SpaceExceededException e ) {+ }++ //if ((query.neededResults() > 0) && (container.size() > query.neededResults())) remove(true, true);+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(+ this.query.id(true),+ SearchEventType.PRESORT,+ resourceName,+ index.size(),+ System.currentTimeMillis() - timer), false);+ }public long getEventTime() {return this.eventTime;@@ -357,7 +556,6 @@ public final class SearchEvent {}protected void cleanup() {- this.cleanupState = true;// stop all threadsif ( this.primarySearchThreadsL != null ) {@@ -383,20 +581,6 @@ public final class SearchEvent {}}- // call the worker threads and ask them to stop- for ( final SnippetWorker w : this.workerThreads ) {- if ( w != null && w.isAlive() ) {- w.pleaseStop();- w.interrupt();- // the interrupt may occur during a MD5 computation which is resistant against interruption- // therefore set some more interrupts on the process- int ic = 10;- while ( ic-- > 0 & w.isAlive() ) {- w.interrupt();- }- }- }-// clear all data structuresif (this.preselectedPeerHashes != null) this.preselectedPeerHashes.clear();if (this.localSearchThread != null && this.localSearchThread.isAlive()) this.localSearchThread.interrupt();@@ -448,47 +632,35 @@ public final class SearchEvent {return this.heuristics.get(urlhash);}}-- protected boolean workerAlive() {- if ( this.workerThreads == null ) {- return false;- }- for ( final SnippetWorker w : this.workerThreads ) {- if ( w != null && w.isAlive() ) {- return true;- }- }- return false;- }- public void add(- final List<URIMetadataNode> index,+ public void addNodes(+ final List<URIMetadataNode> nodeList,final Map<String, ReversibleScoreMap<String>> facets, // a map from a field name to scored valuesfinal Map<String, String> solrsnippets, // a map from urlhash to snippet textfinal boolean local,final String resourceName,final int fullResource) {- this.rankingProcess.addBegin();+ this.addBegin();this.snippets.putAll(solrsnippets);- assert (index != null);- if (index.isEmpty()) return;+ assert (nodeList != null);+ if (nodeList.isEmpty()) return;if (local) {- this.query.local_solr_stored.set(fullResource);+ this.local_solr_stored.set(fullResource);} else {assert fullResource >= 0 : "fullResource = " + fullResource;- this.query.remote_stored.addAndGet(fullResource);- this.query.remote_peerCount.incrementAndGet();+ this.remote_stored.addAndGet(fullResource);+ this.remote_peerCount.incrementAndGet();}long timer = System.currentTimeMillis();// normalize entries- int is = index.size();+ int is = nodeList.size();EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEventType.NORMALIZING, resourceName, is, System.currentTimeMillis() - timer), false);if (!local) {- this.rankingProcess.receivedRemoteReferences.addAndGet(is);+ this.receivedRemoteReferences.addAndGet(is);}// iterate over normalized entries and select some that are better than currently stored@@ -556,10 +728,9 @@ public final class SearchEvent {}}-// apply all constraintstry {- pollloop: for (URIMetadataNode iEntry: index) {+ pollloop: for (URIMetadataNode iEntry: nodeList) {if ( !this.query.urlMask_isCatchall ) {// check url mask@@ -569,18 +740,18 @@ public final class SearchEvent {}// doublecheck for urls- if (this.rankingProcess.urlhashes.has(iEntry.hash())) {+ if (this.urlhashes.has(iEntry.hash())) {continue pollloop;}// increase flag countsfor ( int j = 0; j < 32; j++ ) {- if (iEntry.flags().get(j)) this.rankingProcess.flagCount()[j]++;+ if (iEntry.flags().get(j)) this.flagCount()[j]++;}// check constraintsBitfield flags = iEntry.flags();- if (!this.rankingProcess.testFlags(flags)) continue pollloop;+ if (!this.testFlags(flags)) continue pollloop;// check document domainif (this.query.contentdom.getCode() > 0 &&@@ -603,10 +774,10 @@ public final class SearchEvent {}// finally extend the double-check and insert result to stack- this.rankingProcess.urlhashes.putUnique(iEntry.hash());+ this.urlhashes.putUnique(iEntry.hash());rankingtryloop: while (true) {try {- this.nodeStack.put(new ReverseElement<URIMetadataNode>(iEntry, this.rankingProcess.order.cardinal(iEntry))); // inserts the element and removes the worst (which is smallest)+ this.nodeStack.put(new ReverseElement<URIMetadataNode>(iEntry, this.order.cardinal(iEntry))); // inserts the element and removes the worst (which is smallest)break rankingtryloop;} catch ( final ArithmeticException e ) {// this may happen if the concurrent normalizer changes values during cardinal computation@@ -614,19 +785,11 @@ public final class SearchEvent {}}// increase counter for statistics- if (local) this.query.local_solr_available.incrementAndGet(); else this.query.remote_available.incrementAndGet();+ if (local) this.local_solr_available.incrementAndGet(); else this.remote_available.incrementAndGet();}} catch ( final SpaceExceededException e ) {}- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEventType.PRESORT, resourceName, index.size(), System.currentTimeMillis() - timer), false);- }-- private long waitTimeRecommendation() {- return this.maxExpectedRemoteReferences.get() == 0 ? 0 :- Math.min(maxWaitPerResult,- Math.min(- maxWaitPerResult * this.expectedRemoteReferences.get() / this.maxExpectedRemoteReferences.get(),- maxWaitPerResult * (100 - Math.min(100, this.rankingProcess.receivedRemoteReferences.get())) / 100));+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEventType.PRESORT, resourceName, nodeList.size(), System.currentTimeMillis() - timer), false);}public void addExpectedRemoteReferences(int x) {@@ -636,59 +799,44 @@ public final class SearchEvent {this.expectedRemoteReferences.addAndGet(x);}- private URIMetadataNode takeRWI(final boolean skipDoubleDom, final long waitingtime) {+ /**+ * Take one best entry from the rwiStack and create a node entry out of it.+ * There is no waiting or blocking; if no entry is available this just returns null+ * If the sjupDoubleDom option is selected, only different hosts are returned until no such rwi exists.+ * Then the best entry from domain stacks are returned.+ * @param skipDoubleDom+ * @return a node from a rwi entry if one exist or null if not+ */+ private URIMetadataNode pullOneRWI(final boolean skipDoubleDom) {// returns from the current RWI list the best entry and removes this entry from the listWeakPriorityBlockingQueue<WordReferenceVars> m;WeakPriorityBlockingQueue.Element<WordReferenceVars> rwi = null;- WeakPriorityBlockingQueue.Element<URIMetadataNode> page;- // take one entry from the stack if there are entries on that stack or the feeding is not yet finished- try {- int loops = 0; // a loop counter to terminate the reading if all the results are from the same domain- // wait some time if we did not get so much remote results so far to get a better ranking over remote results- // we wait at most 30 milliseconds to get a maximum total waiting time of 300 milliseconds for 10 results- long wait = Math.min(waitingtime, waitTimeRecommendation());- if ( wait > 0 ) {- //System.out.println("*** RWIProcess extra wait: " + wait + "ms; expectedRemoteReferences = " + this.expectedRemoteReferences.get() + ", receivedRemoteReferences = " + this.receivedRemoteReferences.get() + ", initialExpectedRemoteReferences = " + this.maxExpectedRemoteReferences.get());- Thread.sleep(wait);- }- // loop as long as we can expect that we should get more results- final long timeout = System.currentTimeMillis() + waitingtime;- while (((!this.rankingProcess.feedingIsFinished() && this.rankingProcess.addRunning()) || this.nodeStack.sizeQueue() > 0 || this.rankingProcess.rwiQueueSize() > 0) &&- (this.query.itemsPerPage < 1 || loops++ < this.query.itemsPerPage || (loops > 1000 && !this.rankingProcess.doubleDomCache.isEmpty()))) {- page = null;- rwi = null;- if ( waitingtime <= 0 ) {- page = this.rankingProcess.addRunning() ? this.nodeStack.poll(waitingtime) : this.nodeStack.poll();- if (page == null) rwi = this.rankingProcess.addRunning() ? this.rankingProcess.rwiStack.poll(waitingtime) : this.rankingProcess.rwiStack.poll();- } else {- timeoutloop: while ( System.currentTimeMillis() < timeout ) {- //System.out.println("### RWIProcess feedingIsFinished() = " + feedingIsFinished() + ", this.nodeStack.sizeQueue() = " + this.nodeStack.sizeQueue());- if (this.rankingProcess.feedingIsFinished() && this.rankingProcess.rwiQueueSize() == 0 && this.nodeStack.sizeQueue() == 0) break timeoutloop;- page = this.nodeStack.poll(50);- if (page != null) break timeoutloop;- rwi = this.rankingProcess.rwiStack.poll(50);- if (rwi != null) break timeoutloop;- }- }- if (page != null) return page.getElement();- if (rwi == null) break;+ mainloop: while (true) {+ int c = 0;+ pollloop: while (this.rwiStack.sizeQueue() > 0 && c++ < 10) {+ rwi = this.rwiStack.poll();+ if (rwi == null) return null;if (!skipDoubleDom) {- return this.query.getSegment().fulltext().getMetadata(rwi.getElement(), rwi.getWeight());+ URIMetadataNode node = this.query.getSegment().fulltext().getMetadata(rwi.getElement(), rwi.getWeight());+ if (node == null) continue pollloop;+ return node;}-+// check doubledomfinal String hosthash = rwi.getElement().hosthash();- m = this.rankingProcess.doubleDomCache.get(hosthash);+ m = this.doubleDomCache.get(hosthash);if (m == null) {- synchronized ( this.rankingProcess.doubleDomCache ) {- m = this.rankingProcess.doubleDomCache.get(hosthash);- if ( m == null ) {+ synchronized ( this.doubleDomCache ) {+ m = this.doubleDomCache.get(hosthash);+ if (m == null) {// first appearance of dom. we create an entry to signal that one of that domain was already returned- m = new WeakPriorityBlockingQueue<WordReferenceVars>(this.query.snippetCacheStrategy == null || this.query.snippetCacheStrategy == CacheStrategy.CACHEONLY ? RankingProcess.max_results_preparation_special : RankingProcess.max_results_preparation, false);- this.rankingProcess.doubleDomCache.put(hosthash, m);- return this.query.getSegment().fulltext().getMetadata(rwi.getElement(), rwi.getWeight());+ m = new WeakPriorityBlockingQueue<WordReferenceVars>(this.query.snippetCacheStrategy == null || this.query.snippetCacheStrategy == CacheStrategy.CACHEONLY ? max_results_preparation_special : max_results_preparation, false);+ this.doubleDomCache.put(hosthash, m);+ URIMetadataNode node = this.query.getSegment().fulltext().getMetadata(rwi.getElement(), rwi.getWeight());+ if (node == null) continue pollloop;+ return node;}// second appearances of domm.put(rwi);@@ -697,59 +845,61 @@ public final class SearchEvent {m.put(rwi);}}- } catch ( final InterruptedException e1 ) {- }- if (this.rankingProcess.doubleDomCache.isEmpty()) {- //Log.logWarning("RWIProcess", "doubleDomCache.isEmpty");- return null;- }-- // no more entries in sorted RWI entries. Now take Elements from the doubleDomCache- // find best entry from all caches- WeakPriorityBlockingQueue.Element<WordReferenceVars> bestEntry = null;- WeakPriorityBlockingQueue.Element<WordReferenceVars> o;- final Iterator<WeakPriorityBlockingQueue<WordReferenceVars>> i = this.rankingProcess.doubleDomCache.values().iterator();- while ( i.hasNext() ) {- try {- m = i.next();- } catch ( final ConcurrentModificationException e ) {- Log.logException(e);- continue; // not the best solution...++ // no more entries in sorted RWI entries. Now take Elements from the doubleDomCache+ if (this.doubleDomCache.isEmpty()) {+ //Log.logWarning("SearchEvent", "doubleDomCache.isEmpty");+ return null;+ }++ // find best entry from all caches+ WeakPriorityBlockingQueue.Element<WordReferenceVars> bestEntry = null;+ WeakPriorityBlockingQueue.Element<WordReferenceVars> o;+ final Iterator<WeakPriorityBlockingQueue<WordReferenceVars>> i = this.doubleDomCache.values().iterator();+ doubleloop: while (i.hasNext()) {+ try {+ m = i.next();+ } catch (final ConcurrentModificationException e) {+ Log.logException(e);+ continue mainloop; // not the best solution...+ }+ if (m == null) continue doubleloop;+ if (m.isEmpty()) continue doubleloop;+ if (bestEntry == null) {+ bestEntry = m.peek();+ continue doubleloop;+ }+ o = m.peek();+ if (o == null) continue doubleloop;+ if (o.getWeight() < bestEntry.getWeight()) bestEntry = o;}- if (m == null) continue;- if (m.isEmpty()) continue;if (bestEntry == null) {- bestEntry = m.peek();- continue;+ //Log.logWarning("SearchEvent", "bestEntry == null (1)");+ return null;}- o = m.peek();- if (o == null) continue;- if (o.getWeight() < bestEntry.getWeight()) bestEntry = o;- }- if (bestEntry == null) {- //Log.logWarning("RWIProcess", "bestEntry == null (1)");- return null;- }-- // finally remove the best entry from the doubledom cache- m = this.rankingProcess.doubleDomCache.get(bestEntry.getElement().hosthash());- if (m != null) {- bestEntry = m.poll();- if (bestEntry != null && m.sizeAvailable() == 0) {- synchronized ( this.rankingProcess.doubleDomCache ) {- if (m.sizeAvailable() == 0) {- this.rankingProcess.doubleDomCache.remove(bestEntry.getElement().hosthash());++ // finally remove the best entry from the doubledom cache+ m = this.doubleDomCache.get(bestEntry.getElement().hosthash());+ if (m != null) {+ bestEntry = m.poll();+ if (bestEntry != null && m.sizeAvailable() == 0) {+ synchronized ( this.doubleDomCache ) {+ if (m.sizeAvailable() == 0) {+ this.doubleDomCache.remove(bestEntry.getElement().hosthash());+ }}}}+ if (bestEntry == null) {+ //Log.logWarning("SearchEvent", "bestEntry == null (2)");+ return null;+ }+ URIMetadataNode node = this.query.getSegment().fulltext().getMetadata(bestEntry.getElement(), bestEntry.getWeight());+ if (node == null) continue mainloop;+ return node;}- if (bestEntry == null) {- //Log.logWarning("RWIProcess", "bestEntry == null (2)");- return null;- }- return this.query.getSegment().fulltext().getMetadata(bestEntry.getElement(), bestEntry.getWeight());}-+/*** get one metadata entry from the ranked results. This will be the 'best' entry so far according to the* applied ranking. If there are no more entries left or the timeout limit is reached then null is@@ -757,33 +907,23 @@ public final class SearchEvent {* the future by calling this.feedingIsFinished()** @param skipDoubleDom should be true if it is wanted that double domain entries are skipped- * @param waitingtime the time this method may take for a result computation* @return a metadata entry for a url*/- public URIMetadataNode takeURL(final boolean skipDoubleDom, final long waitingtime) {+ public URIMetadataNode pullOneFilteredFromRWI(final boolean skipDoubleDom) {// returns from the current RWI list the best URL entry and removes this entry from the list- final long timeout = System.currentTimeMillis() + Math.max(10, waitingtime);int p = -1;- long timeleft;- while ( (timeleft = timeout - System.currentTimeMillis()) > 0 ) {- //System.out.println("timeleft = " + timeleft);- final URIMetadataNode page = takeRWI(skipDoubleDom, timeleft);- if (page == null) {- //Log.logWarning("RWIProcess", "takeRWI returned null");- return null; // all time was already wasted in takeRWI to get another element- }+ URIMetadataNode page;+ while ((page = pullOneRWI(skipDoubleDom)) != null) {- if ( !this.query.urlMask_isCatchall ) {+ if (!this.query.urlMask_isCatchall && !page.matches(this.query.urlMask)) {// check url mask- if ( !page.matches(this.query.urlMask) ) {- this.query.misses.add(page.hash());- continue;- }+ this.misses.add(page.hash());+ continue;}// check for more errors- if ( page.url() == null ) {- this.query.misses.add(page.hash());+ if (page.url() == null) {+ this.misses.add(page.hash());continue; // rare case where the url is corrupted}@@ -793,29 +933,23 @@ public final class SearchEvent {(this.query.contentdom == Classification.ContentDomain.AUDIO && page.url().getContentDomain() != Classification.ContentDomain.AUDIO) ||(this.query.contentdom == Classification.ContentDomain.VIDEO && page.url().getContentDomain() != Classification.ContentDomain.VIDEO) ||(this.query.contentdom == Classification.ContentDomain.APP && page.url().getContentDomain() != Classification.ContentDomain.APP)) && this.query.urlMask_isCatchall) {- this.query.misses.add(page.hash());+ this.misses.add(page.hash());continue;}// Check for blacklistif (Switchboard.urlBlacklist.isListed(BlacklistType.SEARCH, page)) {- this.query.misses.add(page.hash());+ this.misses.add(page.hash());continue;}- // contentcontrol- if (Switchboard.getSwitchboard().getConfigBool(- "contentcontrol.enabled", false) == true) {-- FilterEngine f = ContentControlFilterUpdateThread- .getNetworkFilter();- if (f != null) {- if (!f.isListed(page.url(), null)) {- this.query.misses.add(page.hash());- continue;- }+ // content control+ if (Switchboard.getSwitchboard().getConfigBool("contentcontrol.enabled", false)) {+ FilterEngine f = ContentControlFilterUpdateThread.getNetworkFilter();+ if (f != null && !f.isListed(page.url(), null)) {+ this.misses.add(page.hash());+ continue;}-}final String pageurl = page.url().toNormalform(true);@@ -823,27 +957,27 @@ public final class SearchEvent {final String pagetitle = page.dc_title().toLowerCase();// check exclusion- if ( !this.query.getQueryGoal().getExcludeHashes().isEmpty() &&+ if (!this.query.getQueryGoal().getExcludeHashes().isEmpty() &&((QueryParams.anymatch(pagetitle, this.query.getQueryGoal().getExcludeHashes()))|| (QueryParams.anymatch(pageurl.toLowerCase(), this.query.getQueryGoal().getExcludeHashes()))|| (QueryParams.anymatch(pageauthor.toLowerCase(), this.query.getQueryGoal().getExcludeHashes())))) {- this.query.misses.add(page.hash());+ this.misses.add(page.hash());continue;}// check index-of constraintif ((this.query.constraint != null) && (this.query.constraint.get(Condenser.flag_cat_indexof)) && (!(pagetitle.startsWith("index of")))) {final Iterator<byte[]> wi = this.query.getQueryGoal().getIncludeHashes().iterator();- while ( wi.hasNext() ) {+ while (wi.hasNext()) {this.query.getSegment().termIndex().removeDelayed(wi.next(), page.hash());}- this.query.misses.add(page.hash());+ this.misses.add(page.hash());continue;}// check location constraintif ((this.query.constraint != null) && (this.query.constraint.get(Condenser.flag_cat_haslocation)) && (page.lat() == 0.0 || page.lon() == 0.0)) {- this.query.misses.add(page.hash());+ this.misses.add(page.hash());continue;}@@ -854,14 +988,14 @@ public final class SearchEvent {double lonDelta = this.query.lon - lon;double distance = Math.sqrt(latDelta * latDelta + lonDelta * lonDelta); // pythagorasif (distance > this.query.radius) {- this.query.misses.add(page.hash());+ this.misses.add(page.hash());continue;}}// check Scannerif (this.query.filterscannerfail && !Scanner.acceptURL(page.url())) {- this.query.misses.add(page.hash());+ this.misses.add(page.hash());continue;}@@ -882,7 +1016,6 @@ public final class SearchEvent {return page; // accept url}- Log.logWarning("RWIProcess", "loop terminated");return null;}@@ -893,198 +1026,372 @@ public final class SearchEvent {public long getSnippetComputationTime() {return this.snippetComputationAllTime;}-/**- * get topic navigator terms from rankig process- * @param count number of requestd words- * 0 = get default number of words otherwise get- * @return- */+public ScoreMap<String> getTopicNavigator(final int count ) {if (this.topicNavigatorCount > 0 && count >= 0) { //topicNavigatorCount set during init, 0=no nav- return this.rankingProcess.getTopics(count != 0 ? count : this.topicNavigatorCount, 500);+ return this.getTopics(count != 0 ? count : this.topicNavigatorCount, 500);}return null;}- public ResultEntry oneResult(final int item, final long timeout) {- // if there is not yet a worker alive, start one- if (!anyWorkerAlive()) {- deployWorker(Math.min(SNIPPET_WORKER_THREADS, this.query.itemsPerPage), this.query.neededResults());+ public void drainStacksToResult() {+ // we take one entry from both stacks at the same time+ Element<URIMetadataNode> localEntryElement = this.nodeStack.sizeQueue() > 0 ? this.nodeStack.poll() : null;+ URIMetadataNode localEntry = localEntryElement == null ? null : localEntryElement.getElement();+ if (localEntry != null) addResult(getSnippet(localEntry, null));+ if (localEntry == null) {+ URIMetadataNode p2pEntry = pullOneFilteredFromRWI(true);+ if (p2pEntry != null) addResult(getSnippet(p2pEntry, null));+ } else {+ new Thread() {+ public void run() {+ URIMetadataNode p2pEntry = pullOneFilteredFromRWI(true);+ if (p2pEntry != null) addResult(getSnippet(p2pEntry, null));+ }+ }.start();+ }+ }++ /**+ * place the result to the result vector and apply post-ranking+ * @param resultEntry+ */+ public void addResult(ResultEntry resultEntry) {+ if (resultEntry == null) return;+ long ranking = resultEntry.word() == null ? 0 : Long.valueOf(this.order.cardinal(resultEntry.word()));+ ranking += postRanking(resultEntry, new ConcurrentScoreMap<String>() /*this.snippetProcess.rankingProcess.getTopicNavigator(10)*/);+ resultEntry.ranking = ranking;+ this.resultList.put(new ReverseElement<ResultEntry>(resultEntry, ranking)); // remove smallest in case of overflow+ this.addTopics(resultEntry);+ }++ private long postRanking(final ResultEntry rentry, final ScoreMap<String> topwords) {+ long r = 0;++ // for media search: prefer pages with many links+ r += rentry.limage() << this.query.ranking.coeff_cathasimage;+ r += rentry.laudio() << this.query.ranking.coeff_cathasaudio;+ r += rentry.lvideo() << this.query.ranking.coeff_cathasvideo;+ r += rentry.lapp() << this.query.ranking.coeff_cathasapp;++ // apply citation count+ //System.out.println("POSTRANKING CITATION: references = " + rentry.referencesCount() + ", inbound = " + rentry.llocal() + ", outbound = " + rentry.lother());+ r += (128 * rentry.referencesCount() / (1 + 2 * rentry.llocal() + rentry.lother())) << this.query.ranking.coeff_citation;++ // prefer hit with 'prefer' pattern+ if (this.query.prefer.matcher(rentry.url().toNormalform(true)).matches()) r += 256 << this.query.ranking.coeff_prefer;+ if (this.query.prefer.matcher(rentry.title()).matches()) r += 256 << this.query.ranking.coeff_prefer;++ // apply 'common-sense' heuristic using references+ final String urlstring = rentry.url().toNormalform(true);+ final String[] urlcomps = MultiProtocolURI.urlComps(urlstring);+ final String[] descrcomps = MultiProtocolURI.splitpattern.split(rentry.title().toLowerCase());+ for (final String urlcomp : urlcomps) {+ int tc = topwords.get(urlcomp);+ if (tc > 0) r += Math.max(1, tc) << this.query.ranking.coeff_urlcompintoplist;+ }+ for (final String descrcomp : descrcomps) {+ int tc = topwords.get(descrcomp);+ if (tc > 0) r += Math.max(1, tc) << this.query.ranking.coeff_descrcompintoplist;+ }++ // apply query-in-result matching+ final HandleSet urlcomph = Word.words2hashesHandles(urlcomps);+ final HandleSet descrcomph = Word.words2hashesHandles(descrcomps);+ final Iterator<byte[]> shi = this.query.getQueryGoal().getIncludeHashes().iterator();+ byte[] queryhash;+ while (shi.hasNext()) {+ queryhash = shi.next();+ if (urlcomph.has(queryhash)) r += 256 << this.query.ranking.coeff_appurl;+ if (descrcomph.has(queryhash)) r += 256 << this.query.ranking.coeff_app_dc_title;+ }+ return r;+ }++ public ResultEntry getSnippet(URIMetadataNode page, final CacheStrategy cacheStrategy) {+ if (page == null) return null;++ String solrsnippet = this.snippets.get(ASCII.String(page.hash()));+ if (solrsnippet != null && solrsnippet.length() > 0) {+ final TextSnippet snippet = new TextSnippet(page.hash(), solrsnippet, true, ResultClass.SOURCE_CACHE, "");+ return new ResultEntry(page, this.query.getSegment(), this.peers, snippet, null, 0);+ }++ if (cacheStrategy == null) {+ final TextSnippet snippet = new TextSnippet(+ null,+ page,+ this.snippetFetchWordHashes,+ null,+ ((this.query.constraint != null) && (this.query.constraint.get(Condenser.flag_cat_indexof))),+ SearchEvent.SNIPPET_MAX_LENGTH,+ !this.query.isLocal());+ return new ResultEntry(page, this.query.getSegment(), this.peers, snippet, null, 0); // result without snippet}- // wait until local data is there- while (this.localsearch != null && this.localsearch.isAlive() && this.result.sizeAvailable() < item) try {- if (!anyWorkerAlive()) {- deployWorker(Math.min(SNIPPET_WORKER_THREADS, this.query.itemsPerPage), this.query.neededResults());++ // load snippet+ if (page.url().getContentDomain() == Classification.ContentDomain.TEXT || page.url().getContentDomain() == Classification.ContentDomain.ALL) {+ // attach text snippet+ long startTime = System.currentTimeMillis();+ final TextSnippet snippet = new TextSnippet(+ this.loader,+ page,+ this.snippetFetchWordHashes,+ cacheStrategy,+ ((this.query.constraint != null) && (this.query.constraint.get(Condenser.flag_cat_indexof))),+ 180,+ !this.query.isLocal());+ final long snippetComputationTime = System.currentTimeMillis() - startTime;+ SearchEvent.log.logInfo("text snippet load time for " + page.url() + ": " + snippetComputationTime + ", " + (!snippet.getErrorCode().fail() ? "snippet found" : ("no snippet found (" + snippet.getError() + ")")));++ if (!snippet.getErrorCode().fail()) {+ // we loaded the file and found the snippet+ return new ResultEntry(page, this.query.getSegment(), this.peers, snippet, null, snippetComputationTime); // result with snippet attached+ } else if (cacheStrategy.mustBeOffline()) {+ // we did not demand online loading, therefore a failure does not mean that the missing snippet causes a rejection of this result+ // this may happen during a remote search, because snippet loading is omitted to retrieve results faster+ return new ResultEntry(page, this.query.getSegment(), this.peers, null, null, snippetComputationTime); // result without snippet+ } else {+ // problems with snippet fetch+ if (this.snippetFetchWordHashes.has(Segment.catchallHash)) {+ // we accept that because the word cannot be on the page+ return new ResultEntry(page, this.query.getSegment(), this.peers, null, null, 0);+ }+ final String reason = "no text snippet; errorCode = " + snippet.getErrorCode();+ if (this.deleteIfSnippetFail) {+ this.workTables.failURLsRegisterMissingWord(this.query.getSegment().termIndex(), page.url(), this.query.getQueryGoal().getIncludeHashes(), reason);+ }+ SearchEvent.log.logInfo("sorted out url " + page.url().toNormalform(true) + " during search: " + reason);+ return null;}- this.localsearch.join(10);- } catch (InterruptedException e) {}+ }+ return new ResultEntry(page, this.query.getSegment(), this.peers, null, null, 0); // result without snippet+ }+++ public ResultEntry oneResult(final int item, final long timeout) {// check if we already retrieved this item// (happens if a search pages is accessed a second time)final long finishTime = System.currentTimeMillis() + timeout;- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEventType.ONERESULT, "started, item = " + item + ", available = " + this.result.sizeAvailable(), 0, 0), false);-+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEventType.ONERESULT, "started, item = " + item + ", available = " + this.getResultCount(), 0, 0), false);++ // check if we have a success+ if (this.resultList.sizeAvailable() > item) {+ // we have the wanted result already in the result array .. return that+ final ResultEntry re = this.resultList.element(item).getElement();+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEventType.ONERESULT, "prefetched, item = " + item + ", available = " + this.getResultCount() + ": " + re.urlstring(), 0, 0), false);+ return re;+ }+// we must wait some time until the first result page is full to get enough elements for ranking- final long waittimeout = System.currentTimeMillis() + 300;- if (this.remote && item < 10 && !this.rankingProcess.feedingIsFinished()) {+ /*+ if (this.remote && item < 10 && !this.feedingIsFinished()) {// the first 10 results have a very special timing to get most of the remote results ordered// before they are presented on the first lines .. yes sleeps seem to be bad. but how shall we predict how long other// peers will take until they respond?- long sleep = item == 0 ? 400 : (10 - item) * 9; // the first result takes the longest time- try { Thread.sleep(sleep); } catch (final InterruptedException e1) { Log.logException(e1); }- }- int thisRankingQueueSize, lastRankingQueueSize = 0;- if (item < 10) {- while (- ((thisRankingQueueSize = this.rankingProcess.rwiQueueSize()) > 0 || !this.rankingProcess.feedingIsFinished()) &&- (thisRankingQueueSize > lastRankingQueueSize || this.result.sizeAvailable() < item + 1) &&- System.currentTimeMillis() < waittimeout &&- anyWorkerAlive()- ) {- // wait a little time to get first results in the search- lastRankingQueueSize = thisRankingQueueSize;- try { Thread.sleep(20); } catch (final InterruptedException e1) {}+ long stoptime = System.currentTimeMillis() + Math.min(timeout, item == 0 ? 100 : (10 - item) * 9); // the first result takes the longest time+ while (System.currentTimeMillis() < stoptime) {+ //drainStacksToResult();+ try { Thread.sleep(10); } catch (final InterruptedException e) { Log.logException(e); }}}-- if (this.result.sizeAvailable() > item) {+ */++ // now do this as long as needed+ while ((!this.feedingIsFinished() || this.rwiQueueSize() > 0 || this.nodeStack.sizeQueue() > 0) &&+ this.resultList.sizeAvailable() < item + 1 && System.currentTimeMillis() < finishTime) {+ drainStacksToResult();+ try { Thread.sleep(10); } catch (final InterruptedException e) { Log.logException(e); }+ }++ // check if we have a success+ if (this.resultList.sizeAvailable() > item) {// we have the wanted result already in the result array .. return that- final ResultEntry re = this.result.element(item).getElement();- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEventType.ONERESULT, "prefetched, item = " + item + ", available = " + this.result.sizeAvailable() + ": " + re.urlstring(), 0, 0), false);+ final ResultEntry re = this.resultList.element(item).getElement();+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEventType.ONERESULT, "fetched, item = " + item + ", available = " + this.getResultCount() + ": " + re.urlstring(), 0, 0), false);return re;}- // finally wait until enough results are there produced from the snippet fetch process- WeakPriorityBlockingQueue.Element<ResultEntry> entry = null;- while (System.currentTimeMillis() < finishTime) {- Log.logInfo("SnippetProcess", "item = " + item + "; anyWorkerAlive=" + anyWorkerAlive() + "; this.rankingProcess.isAlive() = " + this.rankingProcess.isAlive() + "; this.rankingProcess.feedingIsFinished() = " + this.rankingProcess.feedingIsFinished() + "; this.result.sizeAvailable() = " + this.result.sizeAvailable() + ", this.rankingProcess.sizeQueue() = " + this.rankingProcess.rwiQueueSize() + ", this.rankingProcess.nodeStack.sizeAvailable() = " + this.nodeStack.sizeAvailable());+ // no success+ EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEventType.ONERESULT, "not found, item = " + item + ", available = " + this.getResultCount(), 0, 0), false);+ return null;+ }- if (!anyWorkerAlive() && !this.rankingProcess.isAlive() && this.result.sizeAvailable() + this.rankingProcess.rwiQueueSize() + this.nodeStack.sizeAvailable() <= item && this.rankingProcess.feedingIsFinished()) {- break; // the fail case- }+ public ArrayList<WeakPriorityBlockingQueue.Element<ResultEntry>> completeResults(final long waitingtime) {+ final long timeout = System.currentTimeMillis() + waitingtime;+ int i = 0;+ while (this.resultList.sizeAvailable() < this.query.neededResults() && System.currentTimeMillis() < timeout) {+ oneResult(i++, timeout - System.currentTimeMillis());+ }+ return this.resultList.list(Math.min(this.query.neededResults(), this.resultList.sizeAvailable()));+ }- // deploy worker to get more results- if (!anyWorkerAlive()) {- deployWorker(Math.min(SNIPPET_WORKER_THREADS, this.query.itemsPerPage), this.query.neededResults());+ /**+ * delete a specific entry from the search results+ * this is used if the user clicks on a '-' sign beside the search result+ * @param urlhash+ * @return true if an entry was deleted, false otherwise+ */+ protected boolean delete(final String urlhash) {+ final Iterator<Element<ResultEntry>> i = this.resultList.iterator();+ Element<ResultEntry> entry;+ while (i.hasNext()) {+ entry = i.next();+ if (urlhash.equals(ASCII.String(entry.getElement().url().hash()))) {+ i.remove();+ return true;}-- try {entry = this.result.element(item, 50);} catch (final InterruptedException e) {break;}- if (entry != null) break;}+ return false;+ }- // finally, if there is something, return the result- if (entry == null) {- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEventType.ONERESULT, "not found, item = " + item + ", available = " + this.result.sizeAvailable(), 0, 0), false);- return null;- }- final ResultEntry re = entry.getElement();- EventTracker.update(EventTracker.EClass.SEARCH, new ProfilingGraph.EventSearch(this.query.id(true), SearchEventType.ONERESULT, "retrieved, item = " + item + ", available = " + this.result.sizeAvailable() + ": " + re.urlstring(), 0, 0), false);- if (item == this.query.offset + this.query.itemsPerPage - 1) stopAllWorker(); // we don't need more- return re;+ public ReferenceOrder getOrder() {+ return this.order;+ }++ protected boolean feedingIsFinished() {+ return+ this.feedersTerminated.intValue() > (this.remote ? 1 : 0) &&+ this.feedersAlive.get() == 0;}- public ArrayList<WeakPriorityBlockingQueue.Element<ResultEntry>> completeResults(final long waitingtime) {- final long timeout = System.currentTimeMillis() + waitingtime;- while (this.result.sizeAvailable() < this.query.neededResults() && anyWorkerAlive() && System.currentTimeMillis() < timeout) {- try {Thread.sleep(10);} catch (final InterruptedException e) {}- }- return this.result.list(Math.min(this.query.neededResults(), this.result.sizeAvailable()));+ /**+ * method to signal the incoming stack that one feeder has terminated+ */+ public void oneFeederTerminated() {+ this.feedersTerminated.incrementAndGet();+ final int c = this.feedersAlive.decrementAndGet();+ assert c >= 0 : "feeders = " + c;}+ public void oneFeederStarted() {+ this.feedersAlive.addAndGet(1);+ }++ public QueryParams getQuery() {+ return this.query;+ }- private void deployWorker(int deployCount, final int neededResults) {- if (this.cleanupState ||- (this.rankingProcess.feedingIsFinished() && this.rankingProcess.rwiQueueSize() == 0 && this.nodeStack.sizeAvailable() == 0) ||- this.result.sizeAvailable() >= neededResults) {- return;+ public int[] flagCount() {+ return this.flagcount;+ }++ protected void addBegin() {+ this.addRunning = true;+ }++ public void addFinalize() {+ this.addRunning = false;+ }++ protected boolean addRunning() {+ return this.addRunning;+ }++ public boolean rwiIsEmpty() {+ if ( !this.rwiStack.isEmpty() ) {+ return false;}- SnippetWorker worker;- if (this.workerThreads == null) {- this.workerThreads = new SnippetWorker[deployCount];- synchronized(this.workerThreads) {try {- for (int i = 0; i < this.workerThreads.length; i++) {- if (this.result.sizeAvailable() >= neededResults ||- (this.rankingProcess.feedingIsFinished() && this.rankingProcess.rwiQueueSize() == 0) && this.nodeStack.sizeAvailable() == 0) {- break;- }- worker = new SnippetWorker(this, this.query.maxtime, this.query.snippetCacheStrategy, neededResults);- worker.start();- this.workerThreads[i] = worker;- if (this.expectedRemoteReferences.get() > 0) {- long wait = this.waitTimeRecommendation();- if (wait > 0) {- try {Thread.sleep(wait);} catch ( InterruptedException e ) {}- }- }- }- } catch (OutOfMemoryError e) {}}- } else {- // there are still worker threads running, but some may be dead.- // if we find dead workers, reanimate them- synchronized(this.workerThreads) {- for (int i = 0; i < this.workerThreads.length; i++) {- if (deployCount <= 0 ||- this.result.sizeAvailable() >= neededResults ||- (this.rankingProcess.feedingIsFinished() && this.rankingProcess.rwiQueueSize() == 0) && this.nodeStack.sizeAvailable() == 0) {- break;- }- if (this.workerThreads[i] == null || !this.workerThreads[i].isAlive()) {- worker = new SnippetWorker(this, this.query.maxtime, this.query.snippetCacheStrategy, neededResults);- worker.start();- this.workerThreads[i] = worker;- deployCount--;- }- if (this.expectedRemoteReferences.get() > 0) {- long wait = this.waitTimeRecommendation();- if (wait > 0) {- try {Thread.sleep(wait);} catch ( InterruptedException e ) {}- }- }- }+ for ( final WeakPriorityBlockingQueue<WordReferenceVars> s : this.doubleDomCache.values() ) {+ if ( !s.isEmpty() ) {+ return false;}}+ return true;}- private void stopAllWorker() {- synchronized(this.workerThreads) {- for (int i = 0; i < this.workerThreads.length; i++) {- if (this.workerThreads[i] == null || !this.workerThreads[i].isAlive()) {- continue;- }- this.workerThreads[i].pleaseStop();- this.workerThreads[i].interrupt();+ protected int rwiQueueSize() {+ int c = this.rwiStack.sizeQueue();+ for ( final WeakPriorityBlockingQueue<WordReferenceVars> s : this.doubleDomCache.values() ) {+ c += s.sizeQueue();+ }+ return c;+ }++ protected boolean testFlags(final Bitfield flags) {+ if (this.query.constraint == null) return true;+ // test if ientry matches with filter+ // if all = true: let only entries pass that has all matching bits+ // if all = false: let all entries pass that has at least one matching bit+ if (this.query.allofconstraint) {+ for ( int i = 0; i < 32; i++ ) {+ if ((this.query.constraint.get(i)) && (!flags.get(i))) return false;}+ return true;+ }+ for (int i = 0; i < 32; i++) {+ if ((this.query.constraint.get(i)) && (flags.get(i))) return true;}+ return false;}-- private boolean anyWorkerAlive() {- if (this.workerThreads == null || this.workerThreads.length == 0) {- return false;++ protected Map<byte[], ReferenceContainer<WordReference>> searchContainerMap() {+ // direct access to the result maps is needed for abstract generation+ // this is only available if execQuery() was called before+ return this.localSearchInclusion;+ }++ public ScoreMap<String> getTopics(final int maxcount, final long maxtime) {+ // create a list of words that had been computed by statistics over all+ // words that appeared in the url or the description of all urls+ final ScoreMap<String> result = new ConcurrentScoreMap<String>();+ if ( this.ref.sizeSmaller(2) ) {+ this.ref.clear(); // navigators with one entry are not useful}- synchronized(this.workerThreads) {- for (final SnippetWorker workerThread : this.workerThreads) {- if ((workerThread != null) && (workerThread.isAlive()) && (workerThread.busytime() < 10000)) return true;+ final Map<String, Float> counts = new HashMap<String, Float>();+ final Iterator<String> i = this.ref.keys(false);+ String word;+ int c;+ float q, min = Float.MAX_VALUE, max = Float.MIN_VALUE;+ int ic = maxcount;+ long timeout = System.currentTimeMillis() + maxtime;+ while ( ic-- > 0 && i.hasNext() ) {+ word = i.next();+ if ( word == null ) {+ continue;}+ c = this.query.getSegment().getWordCountGuess(word);+ if ( c > 0 ) {+ q = ((float) this.ref.get(word)) / ((float) c);+ min = Math.min(min, q);+ max = Math.max(max, q);+ counts.put(word, q);+ }+ if (System.currentTimeMillis() > timeout) break;}- return false;+ if ( max > min ) {+ for ( final Map.Entry<String, Float> ce : counts.entrySet() ) {+ result.set(ce.getKey(), (int) (((double) maxcount) * (ce.getValue() - min) / (max - min)));+ }+ }+ return this.ref;}- /**- * delete a specific entry from the search results- * this is used if the user clicks on a '-' sign beside the search result- * @param urlhash- * @return true if an entry was deleted, false otherwise- */- protected boolean delete(final String urlhash) {- final Iterator<Element<ResultEntry>> i = this.result.iterator();- Element<ResultEntry> entry;- while (i.hasNext()) {- entry = i.next();- if (urlhash.equals(ASCII.String(entry.getElement().url().hash()))) {- i.remove();- return true;+ private final static Pattern lettermatch = Pattern.compile("[a-z]+");++ public void addTopic(final String[] words) {+ String word;+ for ( final String w : words ) {+ word = w.toLowerCase();+ if ( word.length() > 2+ && "http_html_php_ftp_www_com_org_net_gov_edu_index_home_page_for_usage_the_and_zum_der_die_das_und_the_zur_bzw_mit_blog_wiki_aus_bei_off"+ .indexOf(word) < 0+ && !this.query.getQueryGoal().getIncludeHashes().has(Word.word2hash(word))+ && lettermatch.matcher(word).matches()+ && !Switchboard.badwords.contains(word)+ && !Switchboard.stopwords.contains(word) ) {+ this.ref.inc(word);}}- return false;+ }++ protected void addTopics(final ResultEntry resultEntry) {+ // take out relevant information for reference computation+ if ((resultEntry.url() == null) || (resultEntry.title() == null)) return;+ final String[] descrcomps = MultiProtocolURI.splitpattern.split(resultEntry.title().toLowerCase()); // words in the description++ // add references+ addTopic(descrcomps);}}diff --git a/source/net/yacy/search/query/SearchEventCache.java b/source/net/yacy/search/query/SearchEventCache.javaindex c9cafdc1c..ed2928b38 100644--- a/source/net/yacy/search/query/SearchEventCache.java+++ b/source/net/yacy/search/query/SearchEventCache.java@@ -83,9 +83,7 @@ public class SearchEventCache {event = eventEntry.getValue();if (event == null) continue;if (all || event.getEventTime() + acceptTime < System.currentTimeMillis()) {- if (event.workerAlive()) {- event.cleanup();- }+ event.cleanup();i.remove();cacheDelete++;}@@ -106,14 +104,6 @@ public class SearchEventCache {return event;}- private static int countAliveThreads() {- int alive = 0;- for (final SearchEvent e: lastEvents.values()) {- if (e.workerAlive()) alive++;- }- return alive;- }-public static SearchEvent getEvent(final QueryParams query,final SeedDB peers,@@ -146,7 +136,7 @@ public class SearchEventCache {}if (event == null) {// check if there are too many other searches alive now- Log.logInfo("SearchEventCache", "getEvent: " + lastEvents.size() + " in cache; " + countAliveThreads() + " alive");+ Log.logInfo("SearchEventCache", "getEvent: " + lastEvents.size() + " in cache");// start a new eventSwitchboard sb = Switchboard.getSwitchboard();diff --git a/source/net/yacy/search/query/SnippetWorker.java b/source/net/yacy/search/query/SnippetWorker.javadeleted file mode 100644index 51a484087..000000000--- a/source/net/yacy/search/query/SnippetWorker.java+++ /dev/null@@ -1,263 +0,0 @@-/**- * SnippetWorker- * Copyright 2012 by Michael Peter Christen, [email protected], Frankfurt a. M., Germany- * First released 01.11.2012 at http://yacy.net- *- * This library is free software; you can redistribute it and/or- * modify it under the terms of the GNU Lesser General Public- * License as published by the Free Software Foundation; either- * version 2.1 of the License, or (at your option) any later version.- *- * This library is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU- * Lesser General Public License for more details.- *- * You should have received a copy of the GNU Lesser General Public License- * along with this program in the file lgpl21.txt- * If not, see <http://www.gnu.org/licenses/>.- */--package net.yacy.search.query;--import java.util.Iterator;--import net.yacy.cora.document.ASCII;-import net.yacy.cora.document.MultiProtocolURI;-import net.yacy.cora.document.analysis.Classification;-import net.yacy.cora.federate.yacy.CacheStrategy;-import net.yacy.cora.sorting.ConcurrentScoreMap;-import net.yacy.cora.sorting.ScoreMap;-import net.yacy.cora.sorting.WeakPriorityBlockingQueue.ReverseElement;-import net.yacy.cora.storage.HandleSet;-import net.yacy.document.Condenser;-import net.yacy.kelondro.data.meta.URIMetadataNode;-import net.yacy.kelondro.data.word.Word;-import net.yacy.kelondro.logging.Log;-import net.yacy.kelondro.util.MemoryControl;-import net.yacy.search.index.Segment;-import net.yacy.search.snippet.ResultEntry;-import net.yacy.search.snippet.TextSnippet;-import net.yacy.search.snippet.TextSnippet.ResultClass;--public class SnippetWorker extends Thread {- private final SearchEvent snippetProcess;- private final long timeout; // the date until this thread should try to work- private long lastLifeSign; // when the last time the run()-loop was executed- private final CacheStrategy cacheStrategy;- private final int neededResults;- private boolean shallrun;-- protected SnippetWorker(final SearchEvent snippetProcess, final long maxlifetime, final CacheStrategy cacheStrategy, final int neededResults) {- this.snippetProcess = snippetProcess;- this.cacheStrategy = cacheStrategy;- this.lastLifeSign = System.currentTimeMillis();- this.timeout = System.currentTimeMillis() + Math.max(1000, maxlifetime);- this.neededResults = neededResults;- this.shallrun = true;- }-- @Override- public void run() {-- // start fetching urls and snippets- URIMetadataNode page;- ResultEntry resultEntry;- try {- while (this.shallrun && System.currentTimeMillis() < this.timeout) {- this.lastLifeSign = System.currentTimeMillis();-- if (MemoryControl.shortStatus()) {- Log.logWarning("SnippetProcess", "shortStatus");- break;- }-- // check if we have enough; we stop only if we can fetch online; otherwise its better to run this to get better navigation- if ((this.cacheStrategy == null || this.cacheStrategy.isAllowedToFetchOnline()) && this.snippetProcess.result.sizeAvailable() >= this.neededResults) {- Log.logWarning("SnippetProcess", this.snippetProcess.result.sizeAvailable() + " = result.sizeAvailable() >= this.neededResults = " + this.neededResults);- break;- }-- // check if we can succeed if we try to take another url- if (this.snippetProcess.rankingProcess.feedingIsFinished() && this.snippetProcess.rankingProcess.rwiQueueSize() == 0 && this.snippetProcess.nodeStack.sizeAvailable() == 0) {- Log.logWarning("SnippetProcess", "rankingProcess.feedingIsFinished() && rankingProcess.sizeQueue() == 0");- break;- }-- // get next entry- page = this.snippetProcess.takeURL(true, Math.min(500, Math.max(20, this.timeout - System.currentTimeMillis())));- //if (page != null) Log.logInfo("SnippetProcess", "got one page: " + page.metadata().url().toNormalform(true, false));- //if (page == null) page = rankedCache.takeURL(false, this.timeout - System.currentTimeMillis());- if (page == null) {- //Log.logWarning("SnippetProcess", "page == null");- break; // no more available- }-- this.setName(page.url().toNormalform(true)); // to support debugging- if (this.snippetProcess.query.filterfailurls && this.snippetProcess.workTables.failURLsContains(page.hash())) {- continue;- }-- resultEntry = fetchSnippet(page, this.cacheStrategy); // does not fetch snippets if snippetMode == 0- if (resultEntry == null) {- continue; // the entry had some problems, cannot be used- }-- //if (result.contains(resultEntry)) continue;- this.snippetProcess.snippetComputationAllTime += resultEntry.snippetComputationTime;-- // place the result to the result vector- // apply post-ranking- long ranking = resultEntry.word() == null ? 0 : Long.valueOf(this.snippetProcess.rankingProcess.order.cardinal(resultEntry.word()));- ranking += postRanking(resultEntry, new ConcurrentScoreMap<String>() /*this.snippetProcess.rankingProcess.getTopicNavigator(10)*/);- resultEntry.ranking = ranking;- this.snippetProcess.result.put(new ReverseElement<ResultEntry>(resultEntry, ranking)); // remove smallest in case of overflow- this.snippetProcess.rankingProcess.addTopics(resultEntry);- }- if (System.currentTimeMillis() >= this.timeout) {- Log.logWarning("SnippetProcess", "worker ended with timeout");- }- //System.out.println("FINISHED WORKER " + id + " FOR " + this.neededResults + " RESULTS, loops = " + loops);- } catch (final Exception e) { Log.logException(e); }- //Log.logInfo("SEARCH", "resultWorker thread " + this.id + " terminated");- }-- protected void pleaseStop() {- this.shallrun = false;- }-- /**- * calculate the time since the worker has had the latest activity- * @return time in milliseconds lasted since latest activity- */- protected long busytime() {- return System.currentTimeMillis() - this.lastLifeSign;- }-- private long postRanking(- final ResultEntry rentry,- final ScoreMap<String> topwords) {-- long r = 0;-- // for media search: prefer pages with many links- r += rentry.limage() << this.snippetProcess.query.ranking.coeff_cathasimage;- r += rentry.laudio() << this.snippetProcess.query.ranking.coeff_cathasaudio;- r += rentry.lvideo() << this.snippetProcess.query.ranking.coeff_cathasvideo;- r += rentry.lapp() << this.snippetProcess.query.ranking.coeff_cathasapp;-- // apply citation count- //System.out.println("POSTRANKING CITATION: references = " + rentry.referencesCount() + ", inbound = " + rentry.llocal() + ", outbound = " + rentry.lother());- r += (128 * rentry.referencesCount() / (1 + 2 * rentry.llocal() + rentry.lother())) << this.snippetProcess.query.ranking.coeff_citation;-- // prefer hit with 'prefer' pattern- if (this.snippetProcess.query.prefer.matcher(rentry.url().toNormalform(true)).matches()) {- r += 256 << this.snippetProcess.query.ranking.coeff_prefer;- }- if (this.snippetProcess.query.prefer.matcher(rentry.title()).matches()) {- r += 256 << this.snippetProcess.query.ranking.coeff_prefer;- }-- // apply 'common-sense' heuristic using references- final String urlstring = rentry.url().toNormalform(true);- final String[] urlcomps = MultiProtocolURI.urlComps(urlstring);- final String[] descrcomps = MultiProtocolURI.splitpattern.split(rentry.title().toLowerCase());- int tc;- for (final String urlcomp : urlcomps) {- tc = topwords.get(urlcomp);- if (tc > 0) {- r += Math.max(1, tc) << this.snippetProcess.query.ranking.coeff_urlcompintoplist;- }- }- for (final String descrcomp : descrcomps) {- tc = topwords.get(descrcomp);- if (tc > 0) {- r += Math.max(1, tc) << this.snippetProcess.query.ranking.coeff_descrcompintoplist;- }- }-- // apply query-in-result matching- final HandleSet urlcomph = Word.words2hashesHandles(urlcomps);- final HandleSet descrcomph = Word.words2hashesHandles(descrcomps);- final Iterator<byte[]> shi = this.snippetProcess.query.getQueryGoal().getIncludeHashes().iterator();- byte[] queryhash;- while (shi.hasNext()) {- queryhash = shi.next();- if (urlcomph.has(queryhash)) {- r += 256 << this.snippetProcess.query.ranking.coeff_appurl;- }- if (descrcomph.has(queryhash)) {- r += 256 << this.snippetProcess.query.ranking.coeff_app_dc_title;- }- }-- return r;- }-- private ResultEntry fetchSnippet(final URIMetadataNode page, final CacheStrategy cacheStrategy) {- // Snippet Fetching can has 3 modes:- // 0 - do not fetch snippets- // 1 - fetch snippets offline only- // 2 - online snippet fetch-- // load only urls if there was not yet a root url of that hash- // find the url entry-- String solrsnippet = this.snippetProcess.snippets.get(ASCII.String(page.hash()));- if (solrsnippet != null && solrsnippet.length() > 0) {- final TextSnippet snippet = new TextSnippet(page.hash(), solrsnippet, true, ResultClass.SOURCE_CACHE, "");- return new ResultEntry(page, this.snippetProcess.query.getSegment(), this.snippetProcess.peers, snippet, null, 0);- }-- if (cacheStrategy == null) {- final TextSnippet snippet = new TextSnippet(- null,- page,- this.snippetProcess.snippetFetchWordHashes,- //this.query.queryString,- null,- ((this.snippetProcess.query.constraint != null) && (this.snippetProcess.query.constraint.get(Condenser.flag_cat_indexof))),- SearchEvent.SNIPPET_MAX_LENGTH,- !this.snippetProcess.query.isLocal());- return new ResultEntry(page, this.snippetProcess.query.getSegment(), this.snippetProcess.peers, snippet, null, 0); // result without snippet- }-- // load snippet- if (page.url().getContentDomain() == Classification.ContentDomain.TEXT || page.url().getContentDomain() == Classification.ContentDomain.ALL) {- // attach text snippet- long startTime = System.currentTimeMillis();- final TextSnippet snippet = new TextSnippet(- this.snippetProcess.loader,- page,- this.snippetProcess.snippetFetchWordHashes,- cacheStrategy,- ((this.snippetProcess.query.constraint != null) && (this.snippetProcess.query.constraint.get(Condenser.flag_cat_indexof))),- 180,- !this.snippetProcess.query.isLocal());- final long snippetComputationTime = System.currentTimeMillis() - startTime;- SearchEvent.log.logInfo("text snippet load time for " + page.url() + ": " + snippetComputationTime + ", " + (!snippet.getErrorCode().fail() ? "snippet found" : ("no snippet found (" + snippet.getError() + ")")));-- if (!snippet.getErrorCode().fail()) {- // we loaded the file and found the snippet- return new ResultEntry(page, this.snippetProcess.query.getSegment(), this.snippetProcess.peers, snippet, null, snippetComputationTime); // result with snippet attached- } else if (cacheStrategy.mustBeOffline()) {- // we did not demand online loading, therefore a failure does not mean that the missing snippet causes a rejection of this result- // this may happen during a remote search, because snippet loading is omitted to retrieve results faster- return new ResultEntry(page, this.snippetProcess.query.getSegment(), this.snippetProcess.peers, null, null, snippetComputationTime); // result without snippet- } else {- // problems with snippet fetch- if (this.snippetProcess.snippetFetchWordHashes.has(Segment.catchallHash)) {- // we accept that because the word cannot be on the page- return new ResultEntry(page, this.snippetProcess.query.getSegment(), this.snippetProcess.peers, null, null, 0);- }- final String reason = "no text snippet; errorCode = " + snippet.getErrorCode();- if (this.snippetProcess.deleteIfSnippetFail) {- this.snippetProcess.workTables.failURLsRegisterMissingWord(this.snippetProcess.query.getSegment().termIndex(), page.url(), this.snippetProcess.query.getQueryGoal().getIncludeHashes(), reason);- }- SearchEvent.log.logInfo("sorted out url " + page.url().toNormalform(true) + " during search: " + reason);- return null;- }- }- return new ResultEntry(page, this.snippetProcess.query.getSegment(), this.snippetProcess.peers, null, null, 0); // result without snippet- }-}