Example usage for org.apache.solr.common SolrDocumentList SolrDocumentList

List of usage examples for org.apache.solr.common SolrDocumentList SolrDocumentList

Introduction

In this page you can find the example usage for org.apache.solr.common SolrDocumentList SolrDocumentList.

Prototype

SolrDocumentList

Source Link

Usage

From source file:org.springframework.data.solr.core.SolrTemplateTests.java

License:Apache License

/**
 * @see DATASOLR-83/*from  w  ww .j  ava2s  .co  m*/
 */
@Test
public void testGetByIds() throws SolrServerException, IOException {

    ArgumentCaptor<SolrRequest> captor = ArgumentCaptor.forClass(SolrRequest.class);

    QueryResponse responseMock = Mockito.mock(QueryResponse.class);
    SolrDocumentList resultList = new SolrDocumentList();
    Mockito.when(responseMock.getResults()).thenReturn(resultList);
    Mockito.when(solrServerMock.request(captor.capture())).thenReturn(new NamedList<Object>());

    List<String> ids = Arrays.asList("myId1", "myId2");
    Collection<DocumentWithIndexAnnotations> result = solrTemplate.getById(ids,
            DocumentWithIndexAnnotations.class);

    Mockito.verify(solrServerMock, Mockito.times(1)).request(captor.capture());
    Assert.assertTrue(result.isEmpty());
    Assert.assertArrayEquals(new String[] { "myId1", "myId2" }, captor.getValue().getParams().getParams("ids"));
    Assert.assertEquals("/get", captor.getValue().getPath());
}

From source file:org.teiid.translator.solr.TestSolrUpdateExecution.java

License:Open Source License

@Test
public void testSimpleInsert() throws Exception {
    String query = "insert into example (price, weight, popularity, name, field) "
            + "VALUES ('1.10', '2.23', 5, 'teiid', 'any')";

    SolrInputDocument insert = new SolrInputDocument();
    insert.addField("price", 1.10f);
    insert.addField("weight", 2.23f);
    insert.addField("popularity", 5);
    insert.addField("name", "teiid");
    insert.addField("nis", "any");

    QueryResponse queryResponse = Mockito.mock(QueryResponse.class);
    Mockito.stub(queryResponse.getResults()).toReturn(new SolrDocumentList());

    QueryResponse queryResponse2 = Mockito.mock(QueryResponse.class);
    Mockito.stub(queryResponse2.getResults()).toReturn(new SolrDocumentList());

    UpdateRequest request = helpUpdate(query, queryResponse, queryResponse2);

    List<SolrInputDocument> docs = request.getDocuments();
    assertEquals(1, docs.size());/*from www.  ja va  2 s . c  o m*/
    assertEquals(insert.toString(), docs.get(0).toString());
}

From source file:org.teiid.translator.solr.TestSolrUpdateExecution.java

License:Open Source License

@Test
public void testSimpleUpdate() throws Exception {
    String query = "Update example set field = 'some' where name = 'teiid'";

    SolrDocument doc = new SolrDocument();
    doc.addField("price", 1.10f);
    doc.addField("weight", 2.23f);
    doc.addField("popularity", 5);
    doc.addField("name", "teiid");
    doc.addField("nis", "any");

    SolrDocumentList list = new SolrDocumentList();
    list.add(doc);//from  w w  w. j a  v a2  s  . com

    QueryResponse queryResponse = Mockito.mock(QueryResponse.class);
    Mockito.stub(queryResponse.getResults()).toReturn(list);

    QueryResponse queryResponse2 = Mockito.mock(QueryResponse.class);
    Mockito.stub(queryResponse2.getResults()).toReturn(new SolrDocumentList());

    UpdateRequest request = helpUpdate(query, queryResponse, queryResponse2);
    List<SolrInputDocument> docs = request.getDocuments();
    assertEquals(1, docs.size());

    SolrInputDocument update = new SolrInputDocument();
    update.addField("price", 1.10f);
    update.addField("weight", 2.23f);
    update.addField("popularity", 5);
    update.addField("name", "teiid");
    update.addField("nis", "some");
    assertEquals(update.toString(), docs.get(0).toString());
}

From source file:org.teiid.translator.solr.TestSolrUpdateExecution.java

License:Open Source License

@Test
public void testSimpleDelete() throws Exception {
    String query = "Delete from example where name = 'teiid'";

    SolrDocument doc = new SolrDocument();
    doc.addField("price", 1.10f);
    doc.addField("weight", 2.23f);
    doc.addField("popularity", 5);
    doc.addField("name", "teiid");
    doc.addField("nis", "any");

    SolrDocumentList list = new SolrDocumentList();
    list.add(doc);//  w w  w  . j a v  a 2s  .c om

    QueryResponse queryResponse = Mockito.mock(QueryResponse.class);
    Mockito.stub(queryResponse.getResults()).toReturn(list);

    QueryResponse queryResponse2 = Mockito.mock(QueryResponse.class);
    Mockito.stub(queryResponse2.getResults()).toReturn(new SolrDocumentList());

    UpdateRequest request = helpUpdate(query, queryResponse, queryResponse2);
    List<SolrInputDocument> docs = request.getDocuments();

    UpdateRequest expected = new UpdateRequest();
    expected.deleteById("teiid");

    assertEquals(expected.getDeleteById().toString(), request.getDeleteById().toString());
}

From source file:org.triple_brain.module.solr_search.SearchRelatedTest.java

License:Mozilla Public License

protected SolrDocumentList resultsOfSearchQuery(SolrQuery solrQuery) throws Exception {
    SolrServer solrServer = solrServer();
    QueryResponse queryResponse = solrServer.query(solrQuery);
    return queryResponse.getResults() == null ? new SolrDocumentList()
            : solrServer.query(solrQuery).getResults();
}

From source file:org.wso2.carbon.registry.indexing.service.ContentBasedSearchService.java

License:Open Source License

/**
 * Method to get the SolrDocumentList/*from www.j  a  v  a 2s  . co m*/
 * @param searchQuery search query
 * @param attributes search attributes map
 * @param registry Registry
 * @return SearchResultsBean
 * @throws IndexerException
 * @throws RegistryException
 */
private SearchResultsBean searchContentInternal(String searchQuery, Map<String, String> attributes,
        UserRegistry registry) throws IndexerException, RegistryException {
    SearchResultsBean resultsBean = new SearchResultsBean();
    SolrClient client = SolrClient.getInstance();
    // To verify advance search and metadata search
    //        boolean isMetaDataSearch = true;
    String advanceSearchAttribute = attributes.get(IndexingConstants.ADVANCE_SEARCH);
    if (advanceSearchAttribute != null && advanceSearchAttribute.equals("true")) {
        //            isMetaDataSearch = false;
        attributes.remove(IndexingConstants.ADVANCE_SEARCH);
    }
    SolrDocumentList results = new SolrDocumentList();
    try {
        results = attributes.size() > 0 ? client.query(registry.getTenantId(), attributes)
                : client.query(searchQuery, registry.getTenantId());
    } catch (SolrException e) {
        // catching the solr exception to avoid blank pages for invalid solr query,
        // so that it will return empty list and log the error message.
        log.error("Invalid Search Query, query contains invalid characters", e);
    }

    if (log.isDebugEnabled())
        log.debug("result received " + results);

    List<ResourceData> filteredResults = new ArrayList<ResourceData>();
    // check the authorization again for the filtered results
    for (SolrDocument solrDocument : results) {
        String path = getPathFromId((String) solrDocument.getFirstValue("id"));
        if ((isAuthorized(registry, path, ActionConstants.GET)) && (registry.resourceExists(path))) {
            filteredResults.add(loadResourceByPath(registry, path));
        }
    }

    //commenting this, we don't need to do pagination here, we are using solr pagination.
    /*        MessageContext messageContext = MessageContext.getCurrentMessageContext();
            
            if (((messageContext != null && PaginationUtils.isPaginationHeadersExist(messageContext))
        || PaginationContext.getInstance() != null) && isMetaDataSearch) {
    try {
        PaginationContext paginationContext;
        if (messageContext != null) {
            paginationContext = PaginationUtils.initPaginationContext(messageContext);
        } else {
            paginationContext = PaginationContext.getInstance();
        }
        List<String> authorizedPathList = new ArrayList<String>();
        for (SolrDocument solrDocument : results) {
            if (paginationContext.getLimit() > 0 && authorizedPathList.size() == paginationContext.getLimit()) {
                break;
            }
            String path = getPathFromId((String) solrDocument.getFirstValue("id"));
            if (registry.resourceExists(path) && isAuthorized(registry, path, ActionConstants.GET)) {
                authorizedPathList.add(path);
            }
        }
        String[] authorizedPaths = authorizedPathList.toArray(new String[authorizedPathList.size()]);
            
        // Fix for REGISTRY-3132
        //sortByDateIfRequired(authorizedPaths, registry, paginationContext);
            
        String[] paginatedPaths;
        int start = paginationContext.getStart();
        int count = paginationContext.getCount();
        int rowCount = authorizedPaths.length;
        if (messageContext != null) {
            PaginationUtils.setRowCount(messageContext, Integer.toString(rowCount));
        }
        paginationContext.setLength(authorizedPaths.length);
        int startIndex = start;
        *//*if (start == 1) {
             startIndex = 0;
           } else {
             startIndex = start;
           } *//*
                if (rowCount < start + count) {
                if(rowCount - startIndex < 0) {
                    String msg = "PaginationContext parameter's start index seems to be greater than the limit count. Please verify your parameters";
                    if(log.isDebugEnabled()) {
                        log.debug(msg);
                    }
                    resultsBean.setErrorMessage(msg);
                    return resultsBean;
                }
                paginatedPaths = new String[rowCount - startIndex];
                System.arraycopy(authorizedPaths, startIndex, paginatedPaths, 0, (rowCount - startIndex));
                } else {
                paginatedPaths = new String[count];
                System.arraycopy(authorizedPaths, startIndex, paginatedPaths, 0, count);
                }
                for (String path : paginatedPaths) {
                ResourceData resourceData = loadResourceByPath(registry, path);
                if (resourceData != null) {
                    filteredResults.add(resourceData);
                }
                }
                } finally {
                if (messageContext != null) {
                PaginationContext.destroy();
                }
                }
                        
                } else {
                for (SolrDocument solrDocument : results) {
                String path = getPathFromId((String) solrDocument.getFirstValue("id"));
                if ((isAuthorized(registry, path, ActionConstants.GET))) {
                ResourceData resourceData = loadResourceByPath(registry, path);
                if (resourceData != null) {
                    filteredResults.add(resourceData);
                }
                }
                }
                }*/
    if (log.isDebugEnabled()) {
        log.debug("filtered results " + filteredResults + " for user " + registry.getUserName());
    }
    resultsBean.setResourceDataList(filteredResults.toArray(new ResourceData[filteredResults.size()]));
    return resultsBean;
}

From source file:org.xwiki.query.solr.SolrQueryExecutorTest.java

License:Open Source License

@Test
public void testMultiValuedQueryArgs() throws Exception {
    SolrInstance solr = mock(SolrInstance.class);
    when(solr.query(any(SolrQuery.class))).then(new Answer<Object>() {
        @Override/*from  w  ww  .  ja va2 s  .co m*/
        public Object answer(InvocationOnMock invocation) throws Throwable {
            SolrQuery solrQuery = (SolrQuery) invocation.getArguments()[0];

            Assert.assertArrayEquals(ITERABLE_PARAM_EXPECTED, solrQuery.getParams(ITERABLE_PARAM_NAME));
            Assert.assertArrayEquals(INT_ARR_PARAM_EXPECTED, solrQuery.getParams(INT_ARR_PARAM_NAME));
            Assert.assertArrayEquals(STR_ARR_PARAM_EXPECTED, solrQuery.getParams(STR_ARR_PARAM_NAME));
            Assert.assertEquals(SINGLE_PARAM_EXPECTED, solrQuery.get(SINGLE_PARAM_NAME));

            QueryResponse r = mock(QueryResponse.class);
            when(r.getResults()).thenReturn(new SolrDocumentList());
            return r;
        }
    });

    ParameterizedType solrProviderType = new DefaultParameterizedType(null, Provider.class, SolrInstance.class);
    Provider<SolrInstance> provider = componentManager.getInstance(solrProviderType);
    when(provider.get()).thenReturn(solr);

    DefaultQuery query = new DefaultQuery("TestQuery", null);
    query.bindValue(ITERABLE_PARAM_NAME, ITERABLE_PARAM_VALUE);
    query.bindValue(INT_ARR_PARAM_NAME, INT_ARR_PARAM_VALUE);
    query.bindValue(STR_ARR_PARAM_NAME, STR_ARR_PARAM_VALUE);
    query.bindValue(SINGLE_PARAM_NAME, SINGLE_PARAM_VALUE);

    componentManager.getComponentUnderTest().execute(query);
}

From source file:org.xwiki.search.solr.internal.job.SolrDocumentIteratorTest.java

License:Open Source License

@Test
public void iterate() throws Exception {
    SolrDocumentList firstResults = new SolrDocumentList();
    firstResults.add(createSolrDocument("chess", "A", "B", "", "1.3"));
    firstResults.add(createSolrDocument("chess", "M", "N", "en", "2.4"));

    QueryResponse firstResponse = mock(QueryResponse.class);
    when(firstResponse.getNextCursorMark()).thenReturn("foo");
    when(firstResponse.getResults()).thenReturn(firstResults);

    SolrDocumentList secondResults = new SolrDocumentList();
    secondResults.add(createSolrDocument("tennis", "X", "Y", "fr", "1.1"));

    QueryResponse secondResponse = mock(QueryResponse.class);
    when(secondResponse.getNextCursorMark()).thenReturn("bar");
    when(secondResponse.getResults()).thenReturn(secondResults);

    when(solr.query(any(SolrQuery.class))).thenReturn(firstResponse, secondResponse, secondResponse);

    DocumentIterator<String> iterator = mocker.getComponentUnderTest();

    WikiReference rootReference = new WikiReference("wiki");
    iterator.setRootReference(rootReference);

    List<Pair<DocumentReference, String>> actualResult = new ArrayList<Pair<DocumentReference, String>>();
    while (iterator.hasNext()) {
        actualResult.add(iterator.next());
    }//  w w  w. j  av  a 2  s.  co  m

    SolrReferenceResolver resolver = mocker.getInstance(SolrReferenceResolver.class);
    verify(resolver).getQuery(rootReference);

    List<Pair<DocumentReference, String>> expectedResult = new ArrayList<Pair<DocumentReference, String>>();
    DocumentReference documentReference = new DocumentReference("chess", "A", "B");
    expectedResult.add(new ImmutablePair<DocumentReference, String>(documentReference, "1.3"));
    documentReference = new DocumentReference("chess", "M", "N", "en");
    expectedResult.add(new ImmutablePair<DocumentReference, String>(documentReference, "2.4"));
    documentReference = new DocumentReference("tennis", "X", "Y", "fr");
    expectedResult.add(new ImmutablePair<DocumentReference, String>(documentReference, "1.1"));

    assertEquals(expectedResult, actualResult);
}

From source file:org.zaizi.manifoldcf.agents.output.solrwrapper.SolrWrapperConnector.java

License:Open Source License

/**
 * Returns from the Entity core all the children entities of a specific primary document
 * //  w ww .j  av  a  2 s .  c  o  m
 * ATTENTION : This can be improved accessing with GET only the documentURI doc, then retrieving or entity types or
 * entities ID ( that are there with SMLT fields)
 * 
 * @param documentURI
 * @param configuration
 * @return
 */
private List<String> retrieveChildrenFromSolr(String documentURI, ConfigParams configuration, String field) {
    QueryResponse getResponse;
    SolrQuery getQuery;
    List<String> childrenIds = new ArrayList<String>();
    SolrDocumentList results = new SolrDocumentList();

    HttpSolrClient solrServer = getHttpSolrServer(configuration);

    getQuery = new SolrQuery();
    getQuery.setRequestHandler("/get");
    getQuery.set("ids", documentURI);

    try {
        getResponse = solrServer.query(getQuery);
        results = getResponse.getResults();
        if (results.size() > 0) {
            SolrDocument d = results.get(0);
            childrenIds = (List<String>) d.getFieldValue(field);
        }

    } catch (SolrServerException e) {
        Logging.connectors.error("Error retrieving children for : " + documentURI, e);

    } finally {
        return childrenIds;
    }

}

From source file:org.zaizi.sensefy.api.dto.response.content.SmartAutoCompleteResponseContent.java

License:Open Source License

public SmartAutoCompleteResponseContent() {
    super();//  w w  w.j a  va2s .  c  o  m
    suggestions = new ArrayList<String>();
    entities = new ArrayList<SolrDocument>();
    entityTypes = new ArrayList<EntityType>();
    titles = new SolrDocumentList();
}