Java Code Examples for org.apache.solr.common.util.NamedList#getVal()

The following examples show how to use org.apache.solr.common.util.NamedList#getVal() . 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: SolrInformationServer.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
private NamedList<Object> fixStats(NamedList<Object> namedList)
{
    int sz = namedList.size();

    for (int i = 0; i < sz; i++)
    {
        Object value = namedList.getVal(i);
        if (value instanceof Number)
        {
            Number number = (Number) value;
            if (Float.isInfinite(number.floatValue()) || Float.isNaN(number.floatValue())
                    || Double.isInfinite(number.doubleValue()) || Double.isNaN(number.doubleValue()))
            {
                namedList.setVal(i, null);
            }
        }
    }
    return namedList;
}
 
Example 2
Source File: BaseCloudSolrClient.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public RouteException(ErrorCode errorCode, NamedList<Throwable> throwables, Map<String, ? extends LBSolrClient.Req> routes){
  super(errorCode, throwables.getVal(0).getMessage(), throwables.getVal(0));
  this.throwables = throwables;
  this.routes = routes;

  // create a merged copy of the metadata from all wrapped exceptions
  NamedList<String> metadata = new NamedList<String>();
  for (int i = 0; i < throwables.size(); i++) {
    Throwable t = throwables.getVal(i);
    if (t instanceof SolrException) {
      SolrException e = (SolrException) t;
      NamedList<String> eMeta = e.getMetadata();
      if (null != eMeta) {
        metadata.addAll(eMeta);
      }
    }
  }
  if (0 < metadata.size()) {
    this.setMetadata(metadata);
  }
}
 
Example 3
Source File: TermsResponse.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public TermsResponse(NamedList<NamedList<Object>> termsInfo) {
  for (int i = 0; i < termsInfo.size(); i++) {
    String fieldName = termsInfo.getName(i);
    List<Term> itemList = new ArrayList<>();
    NamedList<Object> items = termsInfo.getVal(i);
    
    for (int j = 0; j < items.size(); j++) {
      String term = items.getName(j);
      Object val = items.getVal(j);
      Term t;
      if (val instanceof NamedList) {
        @SuppressWarnings("unchecked")
        NamedList<Number> termStats = (NamedList<Number>) val;
        t = new Term(term, termStats.get("df").longValue(), termStats.get("ttf").longValue());
      } else {
        t = new Term(term, ((Number) val).longValue());
      }
      itemList.add(t);
    }

    termMap.put(fieldName, itemList);
  }
}
 
Example 4
Source File: MCRSolrProxyServlet.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
static Map<String, String[]> toMultiMap(ModifiableSolrParams solrQueryParameter) {
    NamedList<Object> namedList = solrQueryParameter.toNamedList();
    //disabled for MCR-953 and https://issues.apache.org/jira/browse/SOLR-7508
    //Map<String, String[]> parameters = ModifiableSolrParams.toMultiMap(namedList);
    HashMap<String, String[]> parameters = new HashMap<>();
    for (int i = 0; i < namedList.size(); i++) {
        String name = namedList.getName(i);
        Object val = namedList.getVal(i);
        if (val instanceof String[]) {
            MultiMapSolrParams.addParam(name, (String[]) val, parameters);
        } else {
            MultiMapSolrParams.addParam(name, val.toString(), parameters);
        }
    }
    //end of fix
    return parameters;
}
 
Example 5
Source File: DistributedAlfrescoSolrSpellcheckerIT.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testSpellcheckerOutputFormat() throws Exception
{
    putHandleDefaults();
    QueryResponse response = query(getDefaultTestClient(), true,
            "{\"query\":\"(YYYYY BBBBB AND (id:(1 2 3 4 5 6)))\",\"locales\":[\"en\"], \"templates\": [{\"name\":\"t1\", \"template\":\"%cm:content\"}], \"authorities\": [\"joel\"], \"tenants\": []}",
            params("spellcheck.q", "YYYYY BBBBB", "qt", "/afts", "shards.qt", "/afts", "start", "0", "rows", "100", "spellcheck", "true"));

    NamedList res = response.getResponse();
    NamedList spellcheck = (NamedList)res.get("spellcheck");
    NamedList suggestions = (NamedList)spellcheck.get("suggestions"); // Solr 4 format
    NamedList collation = (NamedList)suggestions.getVal(2); // The third suggestion should be collation in the Solr format.
    String collationQuery = (String)collation.get("collationQuery");
    String collationQueryString = (String)collation.get("collationQueryString");
    int hits = (int)collation.get("hits");
    assertTrue(hits == 3);
    assertTrue(collationQuery.equals("(yyyyyyy bbbbbbb AND (id:(1 2 3 4 5 6)))"));
    assertTrue(collationQueryString.equals("yyyyyyy bbbbbbb"));
}
 
Example 6
Source File: DistributedAlfrescoSolrFacetingIT.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void pivotFaceting_mincountSetTwo_shouldReturnFacetsOriginalMincount() throws Exception
{
    String jsonQuery = "{\"query\":\"(suggest:a)\",\"locales\":[\"en\"], \"templates\": [{\"name\":\"t1\", \"template\":\"%cm:content\"}], \"authorities\": [\"joel\"], \"tenants\": []}";
    putHandleDefaults();

    QueryResponse queryResponse = query(getDefaultTestClient(), true, jsonQuery,
        params("qt", "/afts", "shards.qt", "/afts", "start", "0", "rows", "0", "fl", "score,id", "facet", "true",
            "facet.pivot", "{http://www.alfresco.org/model/content/1.0}content,{http://www.alfresco.org/model/content/1.0}name","facet.pivot.mincount","2"));

    NamedList<List<PivotField>> facetPivot = queryResponse.getFacetPivot();

    List<PivotField> firstLevelValues = facetPivot.getVal(0);
    Assert.assertThat(firstLevelValues.size(), is(1));
    PivotField firstLevelPivot0 = firstLevelValues.get(0);
    Assert.assertThat(firstLevelPivot0.getValue(), is("contenttwo"));
    Assert.assertThat(firstLevelPivot0.getCount(), is(4));

    List<PivotField> firstLevelPivot0Children = firstLevelPivot0.getPivot();
    Assert.assertThat(firstLevelPivot0Children.size(), is(1));
    PivotField secondLevelPivot0 = firstLevelPivot0Children.get(0);
    Assert.assertThat(secondLevelPivot0.getValue(), is("nametwo"));
    Assert.assertThat(secondLevelPivot0.getCount(), is(4));
}
 
Example 7
Source File: AsyncBuildSuggestComponent.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** Convert NamedList (suggester response) to {@link SuggesterResult} */
private SuggesterResult toSuggesterResult(Map<String, SimpleOrderedMap<NamedList<Object>>> suggestionsMap) {
  SuggesterResult result = new SuggesterResult();
  if (suggestionsMap == null) {
    return result;
  }
  // for each token
  for(Map.Entry<String, SimpleOrderedMap<NamedList<Object>>> entry : suggestionsMap.entrySet()) {
    String suggesterName = entry.getKey();
    for (Iterator<Map.Entry<String, NamedList<Object>>> suggestionsIter = entry.getValue().iterator(); suggestionsIter.hasNext();) {
      Map.Entry<String, NamedList<Object>> suggestions = suggestionsIter.next(); 
      String tokenString = suggestions.getKey();
      List<LookupResult> lookupResults = new ArrayList<>();
      NamedList<Object> suggestion = suggestions.getValue();
      // for each suggestion
      for (int j = 0; j < suggestion.size(); j++) {
        String property = suggestion.getName(j);
        if (property.equals(SuggesterResultLabels.SUGGESTIONS)) {
          @SuppressWarnings("unchecked")
          List<NamedList<Object>> suggestionEntries = (List<NamedList<Object>>) suggestion.getVal(j);
          for(NamedList<Object> suggestionEntry : suggestionEntries) {
            String term = (String) suggestionEntry.get(SuggesterResultLabels.SUGGESTION_TERM);
            Long weight = (Long) suggestionEntry.get(SuggesterResultLabels.SUGGESTION_WEIGHT);
            String payload = (String) suggestionEntry.get(SuggesterResultLabels.SUGGESTION_PAYLOAD);
            LookupResult res = new LookupResult(new CharsRef(term), weight, new BytesRef(payload));
            lookupResults.add(res);
          }
        }
        result.add(suggesterName, tokenString, lookupResults);
      }
    }
  }
  return result;
}
 
Example 8
Source File: DistributedAlfrescoSolrFacetingIT.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void pivotFaceting_mincountSetZero_shouldReturnFacetsMincountOne() throws Exception
{
    String jsonQuery = "{\"query\":\"(suggest:a)\",\"locales\":[\"en\"], \"templates\": [{\"name\":\"t1\", \"template\":\"%cm:content\"}], \"authorities\": [\"joel\"], \"tenants\": []}";
    putHandleDefaults();

    QueryResponse queryResponse = query(getDefaultTestClient(), true, jsonQuery,
        params("qt", "/afts", "shards.qt", "/afts", "start", "0", "rows", "0", "fl", "score,id", "facet", "true",
            "facet.pivot", "{http://www.alfresco.org/model/content/1.0}content,{http://www.alfresco.org/model/content/1.0}name","facet.pivot.mincount","0"));

    NamedList<List<PivotField>> facetPivot = queryResponse.getFacetPivot();

    List<PivotField> firstLevelValues = facetPivot.getVal(0);
    Assert.assertThat(firstLevelValues.size(), is(2));
    PivotField firstLevelPivot0 = firstLevelValues.get(0);
    Assert.assertThat(firstLevelPivot0.getValue(), is("contenttwo"));
    Assert.assertThat(firstLevelPivot0.getCount(), is(4));

    List<PivotField> firstLevelPivot0Children = firstLevelPivot0.getPivot();
    Assert.assertThat(firstLevelPivot0Children.size(), is(1));
    PivotField secondLevelPivot0 = firstLevelPivot0Children.get(0);
    Assert.assertThat(secondLevelPivot0.getValue(), is("nametwo"));
    Assert.assertThat(secondLevelPivot0.getCount(), is(4));

    PivotField firstLevelPivot1 = firstLevelValues.get(1);
    Assert.assertThat(firstLevelPivot1.getValue(), is("contentone"));
    Assert.assertThat(firstLevelPivot1.getCount(), is(1));

    List<PivotField> firstLevelPivot1Children = firstLevelPivot1.getPivot();
    Assert.assertThat(firstLevelPivot1Children.size(), is(1));
    PivotField secondLevelPivot1 = firstLevelPivot1Children.get(0);
    Assert.assertThat(secondLevelPivot1.getValue(), is("nameone"));
    Assert.assertThat(secondLevelPivot1.getCount(), is(1));
}
 
Example 9
Source File: AlfrescoSpellCheckBackCompatComponent.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void process(ResponseBuilder responseBuilder) {
    if(!responseBuilder.req.getParams().getBool(SpellCheckComponent.COMPONENT_NAME, false)) {
        return;
    }
    NamedList response = responseBuilder.rsp.getValues();

    NamedList spellcheck = (NamedList)response.get("spellcheck");
    if(spellcheck == null) {
        return;
    }

    NamedList collations = (NamedList)spellcheck.get("collations");
    NamedList suggest = (NamedList)spellcheck.get("suggest");

    if(collations == null && suggest == null) {
        return;
    }

    NamedList collationList = collations != null ? collations : suggest;

    NamedList spellCheckExtras = new NamedList();

    for(int i=0; i<collationList.size(); i++) {
        if("collation".equals(collationList.getName(i))) {
            NamedList collation = (NamedList) collationList.getVal(i);
            String collationQuery = (String) collation.get("collationQuery");
            String collationQueryString = (String) collation.get("collationQueryString");
            spellCheckExtras.add(collationQuery, collationQueryString);
        }
    }

    response.add("spellcheck-extras", spellCheckExtras);
}
 
Example 10
Source File: RewriteFacetCountsComponent.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void processPivot(ResponseBuilder rb, String[] fromParts, String[] toParts, Collection<NamedList<Object>> current, int level)
{
    for(NamedList<Object> entry : current)
    {
        for(int i = 0; i < entry.size(); i++)
        {
            String name = entry.getName(i);
            if(name.equals("field"))
            {
                entry.setVal(i, fromParts[level].trim());
            }
            else if(name.equals("pivot"))
            {
                Collection<NamedList<Object>> pivot = (Collection<NamedList<Object>>)entry.getVal(i);
                processPivot(rb, fromParts, toParts, pivot, level+1);
            }
            else if(name.equals("ranges"))
            {
            	SimpleOrderedMap ranges = (SimpleOrderedMap)entry.getVal(i);
            	processRanges(rb, ranges);
            }
            else
            {
                // leave alone
            }
        }
    }
}
 
Example 11
Source File: BasicDistributedZkTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private Long getNumCommits(HttpSolrClient sourceClient) throws
    SolrServerException, IOException {
  // construct the /admin/metrics URL
  URL url = new URL(sourceClient.getBaseURL());
  String path = url.getPath().substring(1);
  String[] elements = path.split("/");
  String collection = elements[elements.length - 1];
  String urlString = url.toString();
  urlString = urlString.substring(0, urlString.length() - collection.length() - 1);
  try (HttpSolrClient client = getHttpSolrClient(urlString, 15000, 60000)) {
    ModifiableSolrParams params = new ModifiableSolrParams();
    //params.set("qt", "/admin/metrics?prefix=UPDATE.updateHandler&registry=solr.core." + collection);
    params.set("qt", "/admin/metrics");
    params.set("prefix", "UPDATE.updateHandler");
    params.set("registry", "solr.core." + collection);
    // use generic request to avoid extra processing of queries
    QueryRequest req = new QueryRequest(params);
    NamedList<Object> resp = client.request(req);
    @SuppressWarnings({"rawtypes"})
    NamedList metrics = (NamedList) resp.get("metrics");
    @SuppressWarnings({"rawtypes"})
    NamedList uhandlerCat = (NamedList) metrics.getVal(0);
    @SuppressWarnings({"unchecked"})
    Map<String,Object> commits = (Map<String,Object>) uhandlerCat.get("UPDATE.updateHandler.commits");
    return (Long) commits.get("count");
  }
}
 
Example 12
Source File: ReSearcherUtils.java    From solr-researcher with Apache License 2.0 5 votes vote down vote up
/**
 * Contains logic for iterating over spellchecker's suggestions. If any of input parameters is null, just exits. This method
 * iterates over suggestions for one incorrect word (for which parameter <code>suggestions</code> should contain spellchecker's suggestions).
 * 
 * 
 * @param suggestions list of suggestions for some word, so word parameter isn't needed
 * @param processor instance of processor which will handle all suggestions for word
 */
@SuppressWarnings("unchecked")
public static void iterateOverSpellcheckerSuggestionsForWord(NamedList suggestions, SpellcheckerSuggestionProcessor processor) {
  int i = 4;
  // double topFreq = 0;
  
  if (suggestions.getVal(4) instanceof List) {
    // support for new version of Solr (valid after 2009-09-09 in version 1.4)
    List<SimpleOrderedMap> l = (List<SimpleOrderedMap>) suggestions.getVal(4);
    
    i = 0;
    
    while (true) {
      if (l.size() <= i) {
        break;
      }

      processor.process(l.get(i), (String) l.get(i).get("word"));
      
      i++;
    }
  }
  else {
    // old way, before 2009-09-09
    while (true) {
      if (suggestions.size() <= i) {
        break;
      }

      processor.process((NamedList) (suggestions).getVal(i), suggestions.getName(i));
      
      i++;
    }
  }
  
  processor.afterProcessingFinished();
}
 
Example 13
Source File: SchemaResponse.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private static <T> Map<String, T> extractAttributeMap(NamedList<T> namedList) {
  if (namedList == null) return null;
  LinkedHashMap<String, T> result = new LinkedHashMap<>();
  for (int i = 0; i < namedList.size(); i++) {
    T val = namedList.getVal(i);
    String name = namedList.getName(i);
    if (!(val instanceof NamedList) && !(val instanceof List)) {
      result.put(name, val);
    }
  }

  return result;
}
 
Example 14
Source File: QuerySegmenterConfig.java    From query-segmenter with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public QuerySegmenterConfig(NamedList args) {
  segmenter = new QuerySegmenterDefaultImpl();

  NamedList segments = (NamedList) args.get(INIT_ATTR_SEGMENTS);
  for (int i = 0; i < segments.size(); i++) {
    String name = segments.getName(i);
    NamedList values = (NamedList) segments.getVal(i);
    initSegmentType(name, values);
  }
}
 
Example 15
Source File: DebugComponent.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
protected Object merge(Object source, Object dest, Set<String> exclude) {
  if (source == null) return dest;
  if (dest == null) {
    if (source instanceof NamedList) {
      dest = source instanceof SimpleOrderedMap ? new SimpleOrderedMap() : new NamedList();
    } else {
      return source;
    }
  } else {

    if (dest instanceof Collection) {
      // merge as Set
      if (!(dest instanceof Set)) {
        dest = new LinkedHashSet<>((Collection<?>) dest);
      }
      if (source instanceof Collection) {
        ((Collection)dest).addAll((Collection)source);
      } else {
        ((Collection)dest).add(source);
      }
      return dest;
    } else if (source instanceof Number) {
      if (dest instanceof Number) {
        if (source instanceof Double || dest instanceof Double) {
          return ((Number)source).doubleValue() + ((Number)dest).doubleValue();
        }
        return ((Number)source).longValue() + ((Number)dest).longValue();
      }
      // fall through
    } else if (source instanceof String) {
      if (source.equals(dest)) {
        return dest;
      }
      // fall through
    }
  }


  if (source instanceof NamedList && dest instanceof NamedList) {
    NamedList<Object> tmp = new NamedList<>();
    @SuppressWarnings("unchecked")
    NamedList<Object> sl = (NamedList<Object>)source;
    @SuppressWarnings("unchecked")
    NamedList<Object> dl = (NamedList<Object>)dest;
    for (int i=0; i<sl.size(); i++) {
      String skey = sl.getName(i);
      if (exclude.contains(skey)) continue;
      Object sval = sl.getVal(i);
      int didx = -1;

      // optimize case where elements are in same position
      if (i < dl.size()) {
        String dkey = dl.getName(i);
        if (skey == dkey || (skey!=null && skey.equals(dkey))) {
          didx = i;
        }
      }

      if (didx == -1) {
        didx = dl.indexOf(skey, 0);
      }

      if (didx == -1) {
        tmp.add(skey, merge(sval, null, Collections.emptySet()));
      } else {
        dl.setVal(didx, merge(sval, dl.getVal(didx), Collections.emptySet()));
      }
    }
    dl.addAll(tmp);
    return dl;
  }

  // only add to list if JSON is different
  if (source.equals(dest)) return source;

  // merge unlike elements in a list
  List<Object> t = new ArrayList<>();
  t.add(dest);
  t.add(source);
  return t;
}
 
Example 16
Source File: StatsValuesFactory.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings({"unchecked"})
public void accumulate(@SuppressWarnings({"rawtypes"})NamedList stv) {
  if (computeCount) {
    count += (Long) stv.get("count");
  }
  if (computeMissing) {
    missing += (Long) stv.get("missing");
  }
  if (computeCalcDistinct) {
    distinctValues.addAll((Collection<T>) stv.get("distinctValues"));
    countDistinct = distinctValues.size();
  }

  if (computeMinOrMax) {
    updateMinMax((T) stv.get("min"), (T) stv.get("max"));
  }

  if (computeCardinality) {
    byte[] data = (byte[]) stv.get("cardinality");
    HLL other = HLL.fromBytes(data);
    if (hll.getType().equals(HLLType.EMPTY)) {
      // The HLL.union method goes out of it's way not to modify the "other" HLL.
      // Which means in the case of merging into an "EMPTY" HLL (garunteed to happen at
      // least once in every coordination of shard requests) it always clones all
      // of the internal storage -- but since we're going to throw "other" away after
      // the merge, this just means a short term doubling of RAM that we can skip.
      hll = other;
    } else {
      hll.union(other);
    }
  }

  updateTypeSpecificStats(stv);

  @SuppressWarnings({"rawtypes"})
  NamedList f = (NamedList) stv.get(FACETS);
  if (f == null) {
    return;
  }

  for (int i = 0; i < f.size(); i++) {
    String field = f.getName(i);
    @SuppressWarnings({"rawtypes"})
    NamedList vals = (NamedList) f.getVal(i);
    Map<String, StatsValues> addTo = facets.get(field);
    if (addTo == null) {
      addTo = new HashMap<>();
      facets.put(field, addTo);
    }
    for (int j = 0; j < vals.size(); j++) {
      String val = vals.getName(j);
      StatsValues vvals = addTo.get(val);
      if (vvals == null) {
        vvals = createStatsValues(statsField);
        addTo.put(val, vvals);
      }
      vvals.accumulate((NamedList) vals.getVal(j));
    }
  }
}
 
Example 17
Source File: QueryResponse.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings({"rawtypes"})
public void setResponse( NamedList<Object> res )
{
  super.setResponse( res );
  
  // Look for known things
  for( int i=0; i<res.size(); i++ ) {
    String n = res.getName( i );
    if( "responseHeader".equals( n ) ) {
      _header = (NamedList<Object>) res.getVal( i );
    }
    else if( "response".equals( n ) ) {
      _results = (SolrDocumentList) res.getVal( i );
    }
    else if( "sort_values".equals( n ) ) {
      _sortvalues = (NamedList<ArrayList>) res.getVal( i );
    }
    else if( "facet_counts".equals( n ) ) {
      _facetInfo = (NamedList<Object>) res.getVal( i );
      // extractFacetInfo inspects _results, so defer calling it
      // in case it hasn't been populated yet.
    }
    else if( "debug".equals( n ) ) {
      _debugInfo = (NamedList<Object>) res.getVal( i );
      extractDebugInfo( _debugInfo );
    }
    else if( "grouped".equals( n ) ) {
      _groupedInfo = (NamedList<Object>) res.getVal( i );
      extractGroupedInfo( _groupedInfo );
    }
    else if("expanded".equals(n)) {
      NamedList map = (NamedList) res.getVal(i);
      _expandedResults = map.asMap(1);
    }
    else if( "highlighting".equals( n ) ) {
      _highlightingInfo = (NamedList<Object>) res.getVal( i );
      extractHighlightingInfo( _highlightingInfo );
    }
    else if ( "spellcheck".equals( n ) )  {
      _spellInfo = (NamedList<Object>) res.getVal( i );
      extractSpellCheckInfo( _spellInfo );
    }
    else if ("clusters".equals(n)) {
      _clusterInfo = (ArrayList<NamedList<Object>>) res.getVal(i);
      extractClusteringInfo(_clusterInfo);
    }
    else if ("facets".equals(n)) {
      _jsonFacetingInfo = (NamedList<Object>) res.getVal(i);
      // Don't call extractJsonFacetingInfo(_jsonFacetingInfo) here in an effort to do it lazily
    }
    else if ( "suggest".equals( n ) )  {
      _suggestInfo = (Map<String,NamedList<Object>>) res.getVal( i );
      extractSuggesterInfo(_suggestInfo);
    }
    else if ( "stats".equals( n ) )  {
      _statsInfo = (NamedList<Object>) res.getVal( i );
      extractStatsInfo( _statsInfo );
    }
    else if ( "terms".equals( n ) ) {
      _termsInfo = (NamedList<NamedList<Object>>) res.getVal( i );
      extractTermsInfo( _termsInfo );
    }
    else if ( "moreLikeThis".equals( n ) ) {
      _moreLikeThisInfo = (NamedList<SolrDocumentList>) res.getVal( i );
    }
    else if ( CursorMarkParams.CURSOR_MARK_NEXT.equals( n ) ) {
      _cursorMarkNext = (String) res.getVal( i );
    }
  }
  if(_facetInfo != null) extractFacetInfo( _facetInfo );
}
 
Example 18
Source File: AutocompleteResponseWriter.java    From apache-solr-essentials with Apache License 2.0 4 votes vote down vote up
/**
 * Here the writer creates its output.
 * 
 * @param writer the character stream writer.
 * @param request the current {@link SolrQueryRequest}
 * @param response the output response.
 * @throws IOException in case of I/O failure.
 */
@SuppressWarnings("rawtypes")
@Override
public void write(
		final Writer writer, 
		final SolrQueryRequest request, 
		final SolrQueryResponse response) throws IOException {
	
	// 1. Get a reference to values that compound the current response
	final NamedList elements = response.getValues();
	
	// 2. Use a StringBuilder to build the output 
	final StringBuilder builder = new StringBuilder("{")
		.append("query:'")
		.append(request.getParams().get(CommonParams.Q))
		.append("',");
	
	// 3. Get a reference to the object which hold the query result
	final Object value = elements.getVal(1);		
	if (value instanceof ResultContext)
	{
		final ResultContext context = (ResultContext) value;
	
		// The ordered list (actually the page subset) of matched documents
		final DocList ids = context.docs;
		if (ids != null)
		{
			final SolrIndexSearcher searcher = request.getSearcher();
			final DocIterator iterator = ids.iterator();
			builder.append("suggestions:[");
			
			// 4. Iterate over documents
			for (int i = 0; i < ids.size(); i++)
			{
				// 5. For each document we need to get the corresponding "label" attribute
				final Document document = searcher.doc(iterator.nextDoc(), FIELDS);
				if (i > 0)  { builder.append(","); }
				
				// 6. Append the label value to writer output
				builder
					.append("'")
					.append(((String) document.get("label")).replaceAll("'", "\\\\'").replaceAll("\"", "\\\\\""))
					.append("'");
			}
			builder.append("]").append("}");
		}
	}
	
	// 7. and finally write out the built character stream by means of output writer.
	writer.write(builder.toString());
}
 
Example 19
Source File: SolrReturnFields.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private void parseFieldList(String[] fl, SolrQueryRequest req) {
  _wantsScore = false;
  _wantsAllFields = false;
  if (fl == null || fl.length == 0 || fl.length == 1 && fl[0].length()==0) {
    _wantsAllFields = true;
    return;
  }

  NamedList<String> rename = new NamedList<>();
  DocTransformers augmenters = new DocTransformers();
  for (String fieldList : fl) {
    add(fieldList,rename,augmenters,req);
  }
  for( int i=0; i<rename.size(); i++ ) {
    String from = rename.getName(i);
    String to = rename.getVal(i);
    okFieldNames.add( to );
    boolean copy = (reqFieldNames!=null && reqFieldNames.contains(from));
    if(!copy) {
      // Check that subsequent copy/rename requests have the field they need to copy
      for(int j=i+1; j<rename.size(); j++) {
        if(from.equals(rename.getName(j))) {
          rename.setName(j, to); // copy from the current target
          if(reqFieldNames==null) {
            reqFieldNames = new LinkedHashSet<>();
          }
          reqFieldNames.add(to); // don't rename our current target
        }
      }
    }
    augmenters.addTransformer( new RenameFieldTransformer( from, to, copy ) );
  }
  if (rename.size() > 0 ) {
    renameFields = rename.asShallowMap();
  }
  if( !_wantsAllFields && !globs.isEmpty() ) {
    // TODO??? need to fill up the fields with matching field names in the index
    // and add them to okFieldNames?
    // maybe just get all fields?
    // this would disable field selection optimization... i think that is OK
    fields.clear(); // this will get all fields, and use wantsField to limit
  }

  if( augmenters.size() == 1 ) {
    transformer = augmenters.getTransformer(0);
  }
  else if( augmenters.size() > 1 ) {
    transformer = augmenters;
  }
}
 
Example 20
Source File: JSONResponseWriter.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public void writeNamedList(String name, @SuppressWarnings({"rawtypes"})NamedList val) throws IOException {

  if (val instanceof SimpleOrderedMap) {
    super.writeNamedList(name, val);
    return;
  }

  final int sz = val.size();
  indent();

  writeArrayOpener(sz);
  incLevel();

  boolean first = true;
  for (int i=0; i<sz; i++) {
    if (first) {
      first = false;
    } else {
      writeArraySeparator();
    }

    indent();

    final String elementName = val.getName(i);
    final Object elementVal = val.getVal(i);

    /*
     * JSONWriter's writeNamedListAsArrMap turns NamedList("bar"="foo") into [{"foo":"bar"}]
     * but we here wish to turn it into [ {"name":"bar","type":"str","value":"foo"} ] instead.
     *
     * So first we write the <code>{"name":"bar",</code> portion ...
     */
    writeMapOpener(-1);
    if (elementName != null || writeNullName) {
      writeKey("name", false);
      writeVal("name", elementName);
      writeMapSeparator();
    }

    /*
     * ... and then we write the <code>"type":"str","value":"foo"}</code> portion.
     */
    writeTypeAndValueKey = true;
    writeVal(null, elementVal); // passing null since writeVal doesn't actually use name (and we already wrote elementName above)
    if (writeTypeAndValueKey) {
      throw new RuntimeException("writeTypeAndValueKey should have been reset to false by writeVal('"+elementName+"','"+elementVal+"')");
    }
    writeMapCloser();
  }

  decLevel();
  writeArrayCloser();
}