Java Code Examples for org.apache.solr.common.params.SolrParams#getBool()

The following examples show how to use org.apache.solr.common.params.SolrParams#getBool() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpShardHandler.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private boolean canShortCircuit(String[] slices, boolean onlyNrtReplicas, SolrParams params, CloudDescriptor cloudDescriptor) {
  // Are we hosting the shard that this request is for, and are we active? If so, then handle it ourselves
  // and make it a non-distributed request.
  String ourSlice = cloudDescriptor.getShardId();
  String ourCollection = cloudDescriptor.getCollectionName();
  // Some requests may only be fulfilled by replicas of type Replica.Type.NRT
  if (slices.length == 1 && slices[0] != null
      && (slices[0].equals(ourSlice) || slices[0].equals(ourCollection + "_" + ourSlice))  // handle the <collection>_<slice> format
      && cloudDescriptor.getLastPublished() == Replica.State.ACTIVE
      && (!onlyNrtReplicas || cloudDescriptor.getReplicaType() == Replica.Type.NRT)) {
    boolean shortCircuit = params.getBool("shortCircuit", true);       // currently just a debugging parameter to check distrib search on a single node

    String targetHandler = params.get(ShardParams.SHARDS_QT);
    shortCircuit = shortCircuit && targetHandler == null;             // if a different handler is specified, don't short-circuit

    return shortCircuit;
  }
  return false;
}
 
Example 2
Source File: XJoinSearchComponent.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
/**
 * Generate external process results (if they have not already been generated).
 */
@Override
public void prepare(ResponseBuilder rb) throws IOException {
  SolrParams params = rb.req.getParams();
  if (! params.getBool(getName(), false)) {
    return;
  }
    
  XJoinResults<?> results = (XJoinResults<?>)rb.req.getContext().get(getResultsTag());
  if (results != null) {
    return;
  }
    
  // generate external process results, by passing 'external' prefixed parameters
  // from the query string to our factory
  String prefix = getName() + "." + XJoinParameters.EXTERNAL_PREFIX + ".";
  ModifiableSolrParams externalParams = new ModifiableSolrParams();
  for (Iterator<String> it = params.getParameterNamesIterator(); it.hasNext(); ) {
    String name = it.next();
    if (name.startsWith(prefix)) {
      externalParams.set(name.substring(prefix.length()), params.get(name));
    }
  }
  results = factory.getResults(externalParams);
  rb.req.getContext().put(getResultsTag(), results);
}
 
Example 3
Source File: SpellCheckComponent.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void prepare(ResponseBuilder rb) throws IOException {

  SolrParams params = rb.req.getParams();
  if (!params.getBool(COMPONENT_NAME, false)) {
    return;
  }
  SolrSpellChecker spellChecker = getSpellChecker(params);
  if (params.getBool(SPELLCHECK_BUILD, false)) {
    spellChecker.build(rb.req.getCore(), rb.req.getSearcher());
    rb.rsp.add("command", "build");
  } else if (params.getBool(SPELLCHECK_RELOAD, false)) {
    spellChecker.reload(rb.req.getCore(), rb.req.getSearcher());
    rb.rsp.add("command", "reload");
  }
}
 
Example 4
Source File: QueryDocAuthorizationComponent.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
@Override
public void init(NamedList args) {
  SolrParams params = SolrParams.toSolrParams(args);
  this.authField = params.get(AUTH_FIELD_PROP, DEFAULT_AUTH_FIELD);
  log.info("QueryDocAuthorizationComponent authField: " + this.authField);
  this.allRolesToken = params.get(ALL_ROLES_TOKEN_PROP, "");
  log.info("QueryDocAuthorizationComponent allRolesToken: " + this.allRolesToken);
  this.enabled = params.getBool(ENABLED_PROP, false);
  log.info("QueryDocAuthorizationComponent enabled: " + this.enabled);
}
 
Example 5
Source File: PluginInfoHandler.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception 
{
  SolrParams params = req.getParams();
  
  boolean stats = params.getBool( "stats", false );
  rsp.add( "plugins", getSolrInfoBeans( req.getCore(), stats ) );
  rsp.setHttpCaching(false);
}
 
Example 6
Source File: SpellCheckComponent.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public void modifyRequest(ResponseBuilder rb, SearchComponent who, ShardRequest sreq) {
  SolrParams params = rb.req.getParams();
  if (!params.getBool(COMPONENT_NAME, false)) return;
  int purpose = rb.grouping() ? ShardRequest.PURPOSE_GET_TOP_GROUPS : ShardRequest.PURPOSE_GET_TOP_IDS;
  if ((sreq.purpose & purpose) != 0) {
    // fetch at least 5 suggestions from each shard
    int count = sreq.params.getInt(SPELLCHECK_COUNT, 1);
    if (count < 5)  count = 5;
    sreq.params.set(SPELLCHECK_COUNT, count);
    sreq.params.set("spellcheck", "true");
  } else  {
    sreq.params.set("spellcheck", "false");
  }
}
 
Example 7
Source File: DFRSimilarityFactory.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public void init(SolrParams params) {
  super.init(params);
  discountOverlaps = params.getBool("discountOverlaps", true);
  basicModel = parseBasicModel(params.get("basicModel"));
  afterEffect = parseAfterEffect(params.get("afterEffect"));
  normalization = parseNormalization(
      params.get("normalization"), params.get("c"), params.get("mu"), params.get("z"));
}
 
Example 8
Source File: TaggerRequestHandler.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
protected OffsetCorrector getOffsetCorrector(SolrParams params, Callable<String> inputStringProvider) throws Exception {
  final boolean xmlOffsetAdjust = params.getBool(XML_OFFSET_ADJUST, false);
  if (!xmlOffsetAdjust) {
    return null;
  }
  try {
    return new XmlOffsetCorrector(inputStringProvider.call());
  } catch (XMLStreamException e) {
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
        "Expecting XML but wasn't: " + e, e);
  }
}
 
Example 9
Source File: MoreLikeThisComponent.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public void modifyRequest(ResponseBuilder rb, SearchComponent who, ShardRequest sreq) {
  SolrParams params = rb.req.getParams();
  if (!params.getBool(COMPONENT_NAME, false)) return;
  if ((sreq.purpose & ShardRequest.PURPOSE_GET_MLT_RESULTS) == 0
      && (sreq.purpose & ShardRequest.PURPOSE_GET_TOP_IDS) == 0) {
    sreq.params.set(COMPONENT_NAME, "false");
  }
}
 
Example 10
Source File: QueryRelaxerComponent.java    From solr-researcher with Apache License 2.0 5 votes vote down vote up
@Override
public boolean checkComponentShouldProcess(ResponseBuilder rb) {
  SolrParams params = rb.req.getParams();
  if (!params.getBool(COMPONENT_NAME, false)) {
    return false;
  }

  return true;
}
 
Example 11
Source File: MMapDirectoryFactory.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings({"rawtypes"})
public void init(NamedList args) {
  super.init(args);
  SolrParams params = args.toSolrParams();
  maxChunk = params.getInt("maxChunkSize", MMapDirectory.DEFAULT_MAX_CHUNK_SIZE);
  if (maxChunk <= 0){
    throw new IllegalArgumentException("maxChunk must be greater than 0");
  }
  unmapHack = params.getBool("unmap", true);
  preload = params.getBool("preload", false); //default turn-off
}
 
Example 12
Source File: SuggestComponent.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/** 
 * Used in Distributed Search, merges the suggestion results from every shard
 * */
@Override
public void finishStage(ResponseBuilder rb) {
  SolrParams params = rb.req.getParams();
  log.info("SuggestComponent finishStage with : {}", params);
  if (!params.getBool(COMPONENT_NAME, false) || rb.stage != ResponseBuilder.STAGE_GET_FIELDS)
    return;
  int count = params.getInt(SUGGEST_COUNT, 1);
  
  List<SuggesterResult> suggesterResults = new ArrayList<>();
  
  // Collect Shard responses
  for (ShardRequest sreq : rb.finished) {
    for (ShardResponse srsp : sreq.responses) {
      NamedList<Object> resp;
      if((resp = srsp.getSolrResponse().getResponse()) != null) {
        @SuppressWarnings("unchecked")
        Map<String, SimpleOrderedMap<NamedList<Object>>> namedList = 
            (Map<String, SimpleOrderedMap<NamedList<Object>>>) resp.get(SuggesterResultLabels.SUGGEST);
        if (log.isInfoEnabled()) {
          log.info("{} : {}", srsp.getShard(), namedList);
        }
        suggesterResults.add(toSuggesterResult(namedList));
      }
    }
  }
  
  // Merge Shard responses
  SuggesterResult suggesterResult = merge(suggesterResults, count);
  Map<String, SimpleOrderedMap<NamedList<Object>>> namedListResults = 
      new HashMap<>();
  toNamedList(suggesterResult, namedListResults);
  
  rb.rsp.add(SuggesterResultLabels.SUGGEST, namedListResults);
}
 
Example 13
Source File: OntologyUpdateProcessorFactory.java    From BioSolr with Apache License 2.0 5 votes vote down vote up
@Override
public void init(@SuppressWarnings("rawtypes") final NamedList args) {
	if (args != null) {
		SolrParams params = SolrParams.toSolrParams(args);
		this.enabled = params.getBool(ENABLED_PARAM, true);
		if (enabled) {
			// Helper factory validates ontology parameters
			this.helperFactory = new SolrOntologyHelperFactory(params);
		}

		this.annotationField = params.get(ANNOTATION_FIELD_PARAM);
		this.fieldPrefix = params.get(FIELDNAME_PREFIX_PARAM, annotationField + "_");
		this.labelField = params.get(LABEL_FIELD_PARAM, fieldPrefix + LABEL_FIELD_DEFAULT);
		this.uriFieldSuffix = params.get(URI_FIELD_SUFFIX_PARAM, URI_FIELD_SUFFIX);
		this.labelFieldSuffix = params.get(LABEL_FIELD_SUFFIX_PARAM, LABEL_FIELD_SUFFIX);
		String childField = params.get(CHILD_FIELD_PARAM, fieldPrefix + CHILD_FIELD_DEFAULT);
		this.childUriField = childField + uriFieldSuffix;
		this.childLabelField = childField + labelFieldSuffix;
		String parentField = params.get(PARENT_FIELD_PARAM, fieldPrefix + PARENT_FIELD_DEFAULT);
		this.parentUriField = parentField + uriFieldSuffix;
		this.parentLabelField = parentField + labelFieldSuffix;
		this.includeIndirect = params.getBool(INCLUDE_INDIRECT_PARAM, true);
		String descendentField = params.get(DESCENDANT_FIELD_PARAM, fieldPrefix + DESCENDANT_FIELD_DEFAULT);
		this.descendantUriField = descendentField + uriFieldSuffix;
		this.descendantLabelField = descendentField + labelFieldSuffix;
		String ancestorField = params.get(ANCESTOR_FIELD_PARAM, fieldPrefix + ANCESTOR_FIELD_DEFAULT);
		this.ancestorUriField = ancestorField + uriFieldSuffix;
		this.ancestorLabelField = ancestorField + labelFieldSuffix;
		this.includeRelations = params.getBool(INCLUDE_RELATIONS_PARAM, true);
		this.synonymsField = params.get(SYNONYMS_FIELD_PARAM, fieldPrefix + SYNONYMS_FIELD_DEFAULT);
		this.definitionField = params.get(DEFINITION_FIELD_PARAM, fieldPrefix + DEFINITION_FIELD_DEFAULT);
		this.includeParentPaths = params.getBool(PARENT_PATHS_PARAM, false);
		this.includeParentPathLabels = params.getBool(PARENT_PATHS_LABEL_PARAM, false);
		this.parentPathsField = params.get(PARENT_PATHS_FIELD_PARAM, PARENT_PATHS_FIELD_DEFAULT);
	}
}
 
Example 14
Source File: AsyncBuildSuggestComponent.java    From SearchServices with GNU Lesser General Public License v3.0 4 votes vote down vote up
/** 
 * Responsible for using the specified suggester to get the suggestions 
 * for the query and write the results 
 * */
@Override
public void process(ResponseBuilder rb) throws IOException {
  SolrParams params = rb.req.getParams();
  LOG.debug("SuggestComponent process with : " + params);
  if (!params.getBool(COMPONENT_NAME, false) || suggesters.isEmpty()) {
    return;
  }
  
  boolean buildAll = params.getBool(SUGGEST_BUILD_ALL, false);
  boolean reloadAll = params.getBool(SUGGEST_RELOAD_ALL, false);
  Set<SolrSuggester> querySuggesters;
  try {
    querySuggesters = getSuggesters(params);
  } catch(IllegalArgumentException ex) {
    if (!buildAll && !reloadAll) {
      throw ex;
    } else {
      querySuggesters = new HashSet<>();
    }
  }
  
  String query = params.get(SUGGEST_Q);
  if (query == null) {
    query = rb.getQueryString();
    if (query == null) {
      query = params.get(CommonParams.Q);
    }
  }
  
  if (query != null) {
    int count = params.getInt(SUGGEST_COUNT, 1);
    
    boolean highlight = params.getBool(SUGGEST_HIGHLIGHT, false);
boolean allTermsRequired = params.getBool(
		SUGGEST_ALL_TERMS_REQUIRED, true);
String contextFilter = params.get(SUGGEST_CONTEXT_FILTER_QUERY);
if (contextFilter != null) {
	contextFilter = contextFilter.trim();
	if (contextFilter.length() == 0) {
		contextFilter = null;
	}
}
    
    SuggesterOptions options = new SuggesterOptions(new CharsRef(query), count, contextFilter, allTermsRequired, highlight);
    Map<String, SimpleOrderedMap<NamedList<Object>>> namedListResults = 
        new HashMap<>();
    for (SolrSuggester suggester : querySuggesters) {
      SuggesterResult suggesterResult = suggester.getSuggestions(options);
      toNamedList(suggesterResult, namedListResults);
    }
    rb.rsp.add(SuggesterResultLabels.SUGGEST, namedListResults);
  }
}
 
Example 15
Source File: AlfrescoCoreAdminHandler.java    From SearchServices with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Find transactions and acls missing or duplicated in the cores and
 * add them to be reindexed on the next maintenance operation
 * performed by MetadataTracker and AclTracker.
 *
 * Asynchronous execution
 *
 * @param params
 * - core, optional: The name of the SOLR Core
 * @return Response including the action result:
 * - action.status: scheduled, as it will be executed by Trackers on the next maintenance operation
 * - txToReindex: list of Transaction Ids that are going to be reindexed
 * - aclChangeSetToReindex: list of ACL Change Set Ids that are going to be reindexed
 */
NamedList<Object> actionFIX(SolrParams params) throws JSONException
{
    String requestedCoreName = coreName(params);

    var wrapper = new Object()
    {
        final NamedList<Object> response = new SimpleOrderedMap<>();
    };

    if (isNullOrEmpty(requestedCoreName))
    {
        return wrapper.response;
    }

    if (!coreNames().contains(requestedCoreName))
    {
        wrapper.response.add(ACTION_ERROR_MESSAGE_LABEL, UNKNOWN_CORE_MESSAGE + requestedCoreName);
        return wrapper.response;
    }

    if (!isMasterOrStandalone(requestedCoreName)) {
        wrapper.response.add(ACTION_ERROR_MESSAGE_LABEL, UNPROCESSABLE_REQUEST_ON_SLAVE_NODES);
        return wrapper.response;
    }

    Long fromTxCommitTime = params.getLong(FROM_TX_COMMIT_TIME_PARAMETER_NAME);
    Long toTxCommitTime = params.getLong(TO_TX_COMMIT_TIME_PARAMETER_NAME);
    boolean dryRun = params.getBool(DRY_RUN_PARAMETER_NAME, true);
    int maxTransactionsToSchedule = getMaxTransactionToSchedule(params);

    LOGGER.debug("FIX Admin request on core {}, parameters: " +
                FROM_TX_COMMIT_TIME_PARAMETER_NAME + " = {}, " +
                TO_TX_COMMIT_TIME_PARAMETER_NAME + " = {}, " +
                DRY_RUN_PARAMETER_NAME + " = {}, " +
                    MAX_TRANSACTIONS_TO_SCHEDULE_PARAMETER_NAME + " = {}",
                requestedCoreName,
                ofNullable(fromTxCommitTime).map(Object::toString).orElse("N.A."),
                ofNullable(toTxCommitTime).map(Object::toString).orElse("N.A."),
                dryRun,
                maxTransactionsToSchedule);

    coreNames().stream()
            .filter(coreName -> requestedCoreName == null || coreName.equals(requestedCoreName))
            .filter(this::isMasterOrStandalone)
            .forEach(coreName ->
                    wrapper.response.add(
                                coreName,
                                fixOnSpecificCore(coreName, fromTxCommitTime, toTxCommitTime, dryRun, maxTransactionsToSchedule)));

    if (wrapper.response.size() > 0)
    {
        wrapper.response.add(DRY_RUN_PARAMETER_NAME, dryRun);

        ofNullable(fromTxCommitTime).ifPresent(value -> wrapper.response.add(FROM_TX_COMMIT_TIME_PARAMETER_NAME, value));
        ofNullable(toTxCommitTime).ifPresent(value -> wrapper.response.add(TO_TX_COMMIT_TIME_PARAMETER_NAME, value));

        wrapper.response.add(MAX_TRANSACTIONS_TO_SCHEDULE_PARAMETER_NAME, maxTransactionsToSchedule);
        wrapper.response.add(ACTION_STATUS_LABEL, dryRun ? ACTION_STATUS_NOT_SCHEDULED : ACTION_STATUS_SCHEDULED);
    }

    return wrapper.response;
}
 
Example 16
Source File: RealTimePriceComponent.java    From apache-solr-essentials with Apache License 2.0 4 votes vote down vote up
/**
 * Component initialisation.
 */
@SuppressWarnings("rawtypes")
@Override
public void init(final NamedList args) {
	
	// 1.Retrieve the configuration parameters. 
	// First a "dummy" mode flag, which indicates we are running the 
	// example without a database.
	// If the dummy mode is set to true the get the datasource name
	// This component uses a database as external resource, but it could be
	// also a web service. In any case, this is the place where that
	// resource should be initialized.
	final SolrParams params = SolrParams.toSolrParams(args);
	final boolean isInDummyMode = params.getBool("dummy-mode", true);
	if (isInDummyMode) {
		hasBeenCorrectlyInitialised = true;
		return;
	}
	
	final String datasourceName = params.get("datasource-jndi-name", "jdbc/pricesdb");

	// In case you want give a try, this component actually stubs its
	// behaviour.
	// This is because otherwise we should have a database somewhere, we
	// should configure a datasource and so on...
	// The following code is therefore commented and should be used in case
	// you set up a valid datasource
	try {
		// 2. Obtain a reference to the naming context
		final Context ctx = new InitialContext();

		// 3. Lookup the datasource.
		datasource = (DataSource) ctx.lookup(datasourceName);

		// 4. Give a try by opening and immediately opening a connection.
		datasource.getConnection().close();
		
		// 5a. Mark this component as valid
		hasBeenCorrectlyInitialised = false;
	} catch (final Exception exception) {
		exception.printStackTrace();

		// 5b. Mark this component as invalid (no strictly needed)
		hasBeenCorrectlyInitialised = false;
	}
}
 
Example 17
Source File: PayloadScoreQParserPlugin.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public QParser createParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) {
  return new QParser(qstr, localParams, params, req) {
    @Override
    public Query parse() throws SyntaxError {
      String field = localParams.get(QueryParsing.F);
      String value = localParams.get(QueryParsing.V);
      String func = localParams.get("func");
      String operator = localParams.get("operator", DEFAULT_OPERATOR);
      if (!(operator.equalsIgnoreCase(DEFAULT_OPERATOR) || operator.equalsIgnoreCase("or"))) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Supported operators are : or , phrase");
      }
      boolean includeSpanScore = localParams.getBool("includeSpanScore", false);

      if (field == null) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "'f' not specified");
      }

      if (value == null) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "query string missing");
      }

      FieldType ft = req.getCore().getLatestSchema().getFieldType(field);
      Analyzer analyzer = ft.getQueryAnalyzer();
      SpanQuery query;
      try {
        query = PayloadUtils.createSpanQuery(field, value, analyzer, operator);
      } catch (IOException e) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,e);
      }

      if (query == null) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "SpanQuery is null");
      }

      // note: this query(/parser) does not support func=first; 'first' is a payload() value source feature only
      PayloadFunction payloadFunction = PayloadUtils.getPayloadFunction(func);
      if (payloadFunction == null) throw new SyntaxError("Unknown payload function: " + func);

      PayloadDecoder payloadDecoder = req.getCore().getLatestSchema().getPayloadDecoder(field);
      return new PayloadScoreQuery(query, payloadFunction, payloadDecoder, includeSpanScore);
    }
  };
}
 
Example 18
Source File: RealTimeGetComponent.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public void processGetUpdates(ResponseBuilder rb) throws IOException
{
  SolrQueryRequest req = rb.req;
  SolrQueryResponse rsp = rb.rsp;
  SolrParams params = req.getParams();

  if (!params.getBool(COMPONENT_NAME, true)) {
    return;
  }

  String versionsStr = params.get("getUpdates");
  if (versionsStr == null) return;

  UpdateLog ulog = req.getCore().getUpdateHandler().getUpdateLog();
  if (ulog == null) return;

  // handle version ranges
  List<Long> versions = null;
  if (versionsStr.indexOf("...") != -1) {
    versions = resolveVersionRanges(versionsStr, ulog);
  } else {
    versions = StrUtils.splitSmart(versionsStr, ",", true).stream().map(Long::parseLong)
        .collect(Collectors.toList());
  }

  // find fingerprint for max version for which updates are requested
  boolean doFingerprint = params.getBool("fingerprint", false);
  if (doFingerprint) {
    long maxVersionForUpdate = Collections.min(versions, PeerSync.absComparator);
    IndexFingerprint fingerprint = IndexFingerprint.getFingerprint(req.getCore(), Math.abs(maxVersionForUpdate));
    rb.rsp.add("fingerprint", fingerprint);
  }

  List<Object> updates = new ArrayList<>(versions.size());

  long minVersion = Long.MAX_VALUE;

  // TODO: get this from cache instead of rebuilding?
  try (UpdateLog.RecentUpdates recentUpdates = ulog.getRecentUpdates()) {
    for (Long version : versions) {
      try {
        Object o = recentUpdates.lookup(version);
        if (o == null) continue;

        if (version > 0) {
          minVersion = Math.min(minVersion, version);
        }

        // TODO: do any kind of validation here?
        updates.add(o);

      } catch (SolrException | ClassCastException e) {
        log.warn("Exception reading log for updates", e);
      }
    }

    // Must return all delete-by-query commands that occur after the first add requested
    // since they may apply.
    if (params.getBool("skipDbq", false)) {
      updates.addAll(recentUpdates.getDeleteByQuery(minVersion));
    }

    rb.rsp.add("updates", updates);

  }
}
 
Example 19
Source File: MoreLikeThisHandler.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public MoreLikeThisHelper( SolrParams params, SolrIndexSearcher searcher )
{
  this.searcher = searcher;
  this.reader = searcher.getIndexReader();
  this.uniqueKeyField = searcher.getSchema().getUniqueKeyField();
  this.needDocSet = params.getBool(FacetParams.FACET,false);
  
  SolrParams required = params.required();
  String[] fl = required.getParams(MoreLikeThisParams.SIMILARITY_FIELDS);
  List<String> list = new ArrayList<>();
  for (String f : fl) {
    if (!StringUtils.isEmpty(f))  {
      String[] strings = splitList.split(f);
      for (String string : strings) {
        if (!StringUtils.isEmpty(string)) {
          list.add(string);
        }
      }
    }
  }
  String[] fields = list.toArray(new String[list.size()]);
  if( fields.length < 1 ) {
    throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, 
        "MoreLikeThis requires at least one similarity field: "+MoreLikeThisParams.SIMILARITY_FIELDS );
  }
  
  this.mlt = new MoreLikeThis( reader ); // TODO -- after LUCENE-896, we can use , searcher.getSimilarity() );
  mlt.setFieldNames(fields);
  mlt.setAnalyzer( searcher.getSchema().getIndexAnalyzer() );
  
  // configurable params
  
  mlt.setMinTermFreq(       params.getInt(MoreLikeThisParams.MIN_TERM_FREQ,         MoreLikeThis.DEFAULT_MIN_TERM_FREQ));
  mlt.setMinDocFreq(        params.getInt(MoreLikeThisParams.MIN_DOC_FREQ,          MoreLikeThis.DEFAULT_MIN_DOC_FREQ));
  mlt.setMaxDocFreq(        params.getInt(MoreLikeThisParams.MAX_DOC_FREQ,          MoreLikeThis.DEFAULT_MAX_DOC_FREQ));
  mlt.setMinWordLen(        params.getInt(MoreLikeThisParams.MIN_WORD_LEN,          MoreLikeThis.DEFAULT_MIN_WORD_LENGTH));
  mlt.setMaxWordLen(        params.getInt(MoreLikeThisParams.MAX_WORD_LEN,          MoreLikeThis.DEFAULT_MAX_WORD_LENGTH));
  mlt.setMaxQueryTerms(     params.getInt(MoreLikeThisParams.MAX_QUERY_TERMS,       MoreLikeThis.DEFAULT_MAX_QUERY_TERMS));
  mlt.setMaxNumTokensParsed(params.getInt(MoreLikeThisParams.MAX_NUM_TOKENS_PARSED, MoreLikeThis.DEFAULT_MAX_NUM_TOKENS_PARSED));
  mlt.setBoost(            params.getBool(MoreLikeThisParams.BOOST, false ) );
  
  // There is no default for maxDocFreqPct. Also, it's a bit oddly expressed as an integer value 
  // (percentage of the collection's documents count). We keep Lucene's convention here. 
  if (params.getInt(MoreLikeThisParams.MAX_DOC_FREQ_PCT) != null) {
    mlt.setMaxDocFreqPct(params.getInt(MoreLikeThisParams.MAX_DOC_FREQ_PCT));
  }

  boostFields = SolrPluginUtils.parseFieldBoosts(params.getParams(MoreLikeThisParams.QF));
}
 
Example 20
Source File: TestCloudPivotFacet.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
/**
 * Verify that the PivotFields we're lookin at doesn't violate any of the expected 
 * behaviors based on the <code>TRACE_*</code> params found in the base params
 */
private void assertTraceOk(String pivotName, SolrParams baseParams, List<PivotField> constraints) {
  if (null == constraints || 0 == constraints.size()) {
    return;
  }
  final int maxIdx = constraints.size() - 1;
    
  final int min = baseParams.getInt(TRACE_MIN, -1);
  final boolean expectMissing = baseParams.getBool(TRACE_MISS, false);
  final boolean checkCount = "count".equals(baseParams.get(TRACE_SORT, "count"));

  int prevCount = Integer.MAX_VALUE;

  for (int i = 0; i <= maxIdx; i++) {
    final PivotField constraint = constraints.get(i);
    final int count = constraint.getCount();

    if (0 < min) {
      assertTrue(pivotName + ": val #"+i +" of " + maxIdx + 
                 ": count("+count+") < facet.mincount("+min+"): " + constraint,
                 min <= count);
    }
    // missing value must always come last, but only if facet.missing was used
    // and may not exist at all (mincount, none missing for this sub-facet, etc...)
    if ((i < maxIdx) || (!expectMissing)) {
      assertNotNull(pivotName + ": val #"+i +" of " + maxIdx + 
                    " has null value: " + constraint,
                    constraint.getValue());
    }
    // if we are expecting count based sort, then the count of each constraint 
    // must be lt-or-eq the count that came before -- or it must be the last value and 
    // be "missing"
    if (checkCount) {
      assertTrue(pivotName + ": val #"+i +" of" + maxIdx + 
                 ": count("+count+") > prevCount("+prevCount+"): " + constraint,
                 ((count <= prevCount)
                  || (expectMissing && i == maxIdx && null == constraint.getValue())));
      prevCount = count;
    }
  }
}