Example usage for org.apache.solr.response SolrQueryResponse SolrQueryResponse

List of usage examples for org.apache.solr.response SolrQueryResponse SolrQueryResponse

Introduction

In this page you can find the example usage for org.apache.solr.response SolrQueryResponse SolrQueryResponse.

Prototype


public SolrQueryResponse() 

Source Link

Document

// another way of returning an error int errCode; String errMsg;

Usage

From source file:at.newmedialab.lmf.util.solr.suggestion.service.SuggestionService.java

License:Apache License

private SolrQueryResponse query(String query, String df, String[] fields, String[] fqs) {

    SolrQueryResponse rsp = new SolrQueryResponse();

    //append *//from   w  w  w  .  ja  va 2s  .  c  om
    if (!query.endsWith("*")) {
        query = query.trim() + "*";
    }

    //Prepare query
    ModifiableSolrParams params = new ModifiableSolrParams();
    SolrQueryRequest req = new LocalSolrQueryRequest(solrCore, params);
    params.add(CommonParams.Q, query.toLowerCase());
    params.add(CommonParams.DF, df);
    params.add("q.op", "AND");
    params.add(FacetParams.FACET, "true");
    params.add(FacetParams.FACET_LIMIT, internalFacetLimit);
    params.add(FacetParams.FACET_MINCOUNT, "1");
    for (String field : fields) {
        params.add(FacetParams.FACET_FIELD, field);
    }
    if (fqs != null) {
        for (String fq : fqs) {
            params.add(CommonParams.FQ, fq);
        }
    }

    if (spellcheck_enabled) {
        params.add("spellcheck", "true");
        params.add("spellcheck.collate", "true");
    }

    try {
        //execute query and return
        searchHandler.handleRequestBody(req, rsp);
        return rsp;
    } catch (SolrException se) {
        throw se;
    } catch (Exception e) {
        e.printStackTrace();
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "internal server error");
    } finally {
        req.close();
    }
}

From source file:com.adr.bigdata.search.product.fe.BaseSuggestionHandler.java

@Override
public void handleRequest(SolrQueryRequest req, SolrQueryResponse rsp) {
    String cacheKey = SolrParamUtils.transform(req.getParams());
    try {//from ww w.ja  v  a 2  s  .  c  om
        String cacheResponse = this.rdModel.get(cacheKey);
        if (cacheResponse == null) {
            //cacheMiss
            try {
                final Object[] terms = new Object[1];
                suggestionLogic.execute(req, rsp, new Callable() {
                    @Override
                    public void call(Object... args) {
                        terms[0] = args[0];
                    }
                });
                SolrQueryResponse _rsp = new SolrQueryResponse();
                super.handleRequest(req, _rsp);
                suggestionLogic.writeRsp(req, _rsp, terms[0]);
                String result = outerString(req, _rsp);
                if (!zeroResult(_rsp)) {
                    this.rdModel.put(cacheKey, result);
                }
                ModifiableSolrParams params = new ModifiableSolrParams(req.getParams());
                params.set("vincache", true);
                SolrParams _params = SolrParams.wrapDefaults(params, defaults);
                _params = SolrParams.wrapAppended(_params, appends);
                req.setParams(_params);
                rsp.add("vincache", result);
            } catch (Exception e) {
                error(req, rsp);
                getLogger().error("", e);
            }

        } else {
            //cache hit
            ModifiableSolrParams solrParam = new ModifiableSolrParams(req.getParams());
            solrParam.set("vincache", true);
            SolrParams params = SolrParams.wrapAppended(solrParam, appends);
            params = SolrParams.wrapDefaults(params, defaults);
            req.setParams(params);
            rsp.add("vincache", cacheResponse);
        }

    } catch (Exception cacheEx) {
        getLogger().error("fail to get from redis cache.....{}", cacheEx.getMessage());
        try {
            final Object[] terms = new Object[1];

            suggestionLogic.execute(req, rsp, new Callable() {
                @Override
                public void call(Object... args) {
                    terms[0] = args[0];
                }
            });
            super.handleRequest(req, rsp);
            suggestionLogic.writeRsp(req, rsp, terms[0]);
        } catch (Exception e) {
            error(req, rsp);
            getLogger().error("", e);
        }
    }
}

From source file:com.doculibre.constellio.wicket.servlet.SolrServletEmulator.java

License:Open Source License

@SuppressWarnings("deprecation")
public void writeResponse(String solrQuery, RecordCollection collection, ConstellioUser user,
        HttpServletRequest request, HttpServletResponse response) {
    OutputStream outputStream;/*from   ww  w .  j a v a2s  . co  m*/
    try {
        outputStream = response.getOutputStream();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    if (user != null && !user.hasSearchPermission(collection)) {
        throw new RuntimeException("The user doesn't have search permission on the collection");
    } else if (user == null && collection.hasSearchPermission()) {
        throw new RuntimeException("The collection requires a user with search permission");
    } else {
        SimpleSearch simpleSearch = new SimpleSearch();
        simpleSearch.setCollectionName(collection.getName());

        if (solrQuery.contains("facet=constellio")) {
            solrQuery = solrQuery.replace("facet=constellio", "facet=on");
            solrQuery = addConstellioFacets(simpleSearch, solrQuery, collection, user);
            LOGGER.info("Using constellio facets, new query is " + solrQuery);
        }
        ModifiableSolrParams solrParams = new ModifiableSolrParams(
                SolrRequestParsers.parseQueryString(solrQuery));

        String queryType = solrParams.get("qt");
        if (queryType != null && (queryType.toLowerCase().equals("spellchecker")
                || queryType.toLowerCase().equals("spellcheck"))) {
            writeSpellCheckerResponse(simpleSearch, solrParams, collection, user, outputStream);

        } else {
            String cdf = solrParams.get("cdf");
            if (cdf != null && cdf.equals("true")) {
                SearchResultFieldServices searchResultFieldServices = ConstellioSpringUtils
                        .getSearchResultFieldServices();
                List<SearchResultField> fields = searchResultFieldServices.list();
                List<String> fieldNames = new ArrayList<String>();
                for (SearchResultField field : fields) {
                    if (field.getRecordCollection().equals(collection)) {
                        fieldNames.add(field.getIndexField().getName());
                    }
                }
                solrParams.add("fl", StringUtils.join(fieldNames.toArray(), ","));
                solrParams.remove("cdf");
            }
            try {
                SolrServer solrServer = SolrCoreContext.getSolrServer(collection);
                QueryResponse queryResponse = solrServer.query(solrParams);

                if (queryResponse.getStatus() == 0) {
                    String ipAddress = request.getRemoteAddr();
                    simpleSearch.setQuery(solrParams.get("q"));
                    StatsServices statsServices = ConstellioSpringUtils.getStatsServices();
                    statsServices.logSearch(simpleSearch, queryResponse, ipAddress);
                    XMLResponseWriter xmlWriter = new XMLResponseWriter();
                    SolrQueryResponse sResponse = new SolrQueryResponse();
                    sResponse.setAllValues(queryResponse.getResponse());

                    try (OutputStreamWriter out = new OutputStreamWriter(outputStream)) {
                        xmlWriter.write(out, new LocalSolrQueryRequest(null, solrParams), sResponse);
                        out.flush();
                    } catch (IOException e) {
                        throw new RuntimeException("Unable to convert Solr response into XML", e);
                    }
                }
            } catch (SolrException e) {
                // if (!e.logged)
                LOGGER.log(Level.SEVERE, SolrException.toStr(e), e);
                // try {
                // outputStream.write(ExceptionUtils.getFullStackTrace(e).getBytes());
                // } catch (IOException e1) {
                // throw new RuntimeException(e1);
                // }
                // if (!e.logged) SolrException.log(log,e);
                sendErr(e.code(), SolrException.toStr(e), response, outputStream);
            } catch (Throwable e) {
                LOGGER.log(Level.SEVERE, SolrException.toStr(e), e);
                // try {
                // outputStream.write(ExceptionUtils.getFullStackTrace(e).getBytes());
                // } catch (IOException e1) {
                // throw new RuntimeException(e1);
                // }
                // SolrException.log(log,e);
                sendErr(500, SolrException.toStr(e), response, outputStream);
            }

            // final SolrCore core =
            // SolrCoreContext.getCores().getCore(collection.getName());
            // // SolrServletRequest solrReq = new SolrServletRequest(core,
            // request);
            // SolrQueryRequest solrReq = new LocalSolrQueryRequest(core,
            // solrParams);
            // SolrQueryResponse solrRsp = new SolrQueryResponse();
            // try {
            //
            // SolrRequestHandler handler =
            // core.getRequestHandler(solrReq.getParams().get(CommonParams.QT));
            // if (handler==null) {
            // LOGGER.log(Level.WARNING, "Unknown Request Handler '" +
            // solrReq.getParams().get(CommonParams.QT)
            // + "' :" + solrReq);
            // // log.warn("Unknown Request Handler '" +
            // solrReq.getQueryType() +"' :" + solrReq);
            // throw new
            // SolrException(SolrException.ErrorCode.BAD_REQUEST,"Unknown Request Handler '"
            // + solrReq.getParams().get(CommonParams.QT) + "'");
            // }
            // core.execute(handler, solrReq, solrRsp );
            // if (solrRsp.getException() == null) {
            // String ipAddress = request.getRemoteAddr();
            //
            // simpleSearch.setQuery(solrParams.get("q"));
            // QueryResponse qrsp = new QueryResponse();
            // qrsp.setResponse(getParsedResponse(solrReq, solrRsp));
            //
            // StatsServices statsServices =
            // ConstellioSpringUtils.getStatsServices();
            // statsServices.logSearch(simpleSearch, qrsp, ipAddress);
            //
            // QueryResponseWriter responseWriter =
            // core.getQueryResponseWriter(solrReq);
            // // Now write it out
            // final String ct = responseWriter.getContentType(solrReq,
            // solrRsp);
            // // don't call setContentType on null
            // if (null != ct) response.setContentType(ct);
            // if (responseWriter instanceof BinaryQueryResponseWriter) {
            // BinaryQueryResponseWriter binWriter =
            // (BinaryQueryResponseWriter) responseWriter;
            // binWriter.write(outputStream, solrReq, solrRsp);
            // } else {
            // String charset =
            // ContentStreamBase.getCharsetFromContentType(ct);
            // Writer out = (charset == null ||
            // charset.equalsIgnoreCase("UTF-8"))
            // ? new OutputStreamWriter(outputStream, UTF8)
            // : new OutputStreamWriter(outputStream, charset);
            // out = new FastWriter(out);
            // responseWriter.write(out, solrReq, solrRsp);
            // out.flush();
            // }
            // } else {
            // Exception e = solrRsp.getException();
            // LOGGER.log(Level.SEVERE, SolrException.toStr(e), e);
            // //
            // outputStream.write(ExceptionUtils.getFullStackTrace(e).getBytes());
            // int rc=500;
            // if (e instanceof SolrException) {
            // rc=((SolrException)e).code();
            // }
            // sendErr(rc, SolrException.toStr(e), response, outputStream);
            // }
            // } catch (SolrException e) {
            // // if (!e.logged)
            // LOGGER.log(Level.SEVERE, SolrException.toStr(e), e);
            // // try {
            // //
            // outputStream.write(ExceptionUtils.getFullStackTrace(e).getBytes());
            // // } catch (IOException e1) {
            // // throw new RuntimeException(e1);
            // // }
            // // if (!e.logged) SolrException.log(log,e);
            // sendErr(e.code(), SolrException.toStr(e), response,
            // outputStream);
            // } catch (Throwable e) {
            // LOGGER.log(Level.SEVERE, SolrException.toStr(e), e);
            // // try {
            // //
            // outputStream.write(ExceptionUtils.getFullStackTrace(e).getBytes());
            // // } catch (IOException e1) {
            // // throw new RuntimeException(e1);
            // // }
            // // SolrException.log(log,e);
            // sendErr(500, SolrException.toStr(e), response, outputStream);
            // } finally {
            // // This releases the IndexReader associated with the request
            // solrReq.close();
            // }
        }
    }
}

From source file:com.memonews.solr.handler.component.HighlightQueryComponentTest.java

License:Apache License

@Test
public void shouldAddHighlightQuery() throws Exception {
    String query = "apache AND solr";
    SolrQueryRequest q = req("q", query, "defType", "edismax");
    final SearchComponent c = h.getCore().getSearchComponent("highlightQuery");
    ResponseBuilder rb = new ResponseBuilder(q, new SolrQueryResponse(), Arrays.asList(c));
    rb.doHighlights = true;/* www  .ja va 2 s  .c  o  m*/

    c.process(rb);

    assertEquals("+text:apache +text:solr", rb.getHighlightQuery().toString());
}

From source file:com.memonews.solr.handler.component.HighlightQueryComponentTest.java

License:Apache License

@Test
public void shouldNotAddHighlightQuery() throws Exception {

    final SearchComponent c = h.getCore().getSearchComponent("highlightQuery");

    ResponseBuilder rb = new ResponseBuilder(req(), new SolrQueryResponse(), Arrays.asList(c));
    rb.doHighlights = false;/*from  w  ww .  j  a  v  a 2 s .c o m*/
    c.process(rb);

    assertNull(rb.getHighlightQuery());
}

From source file:com.memonews.solr.handler.component.HighlightQueryComponentTest.java

License:Apache License

@Test
public void shouldRemoveFieldFromQuery() throws Exception {

    String query = "apache AND solr NOT title:test OR name:tz";
    SolrQueryRequest q = req("q", query, "defType", "edismax");
    final SearchComponent c = h.getCore().getSearchComponent("highlightQuery");
    ResponseBuilder rb = new ResponseBuilder(q, new SolrQueryResponse(), Arrays.asList(c));
    rb.doHighlights = true;//from  ww w. j ava 2  s  .  c  om

    c.process(rb);

    assertEquals("+text:apache +text:solr -() name:tz", rb.getHighlightQuery().toString());
}

From source file:com.memonews.solr.handler.component.HighlightQueryComponentTest.java

License:Apache License

@Test
public void shouldRomoveFieldsFromQuery() throws Exception {
    String qstr = "title:\"The Right Way\"~10 AND text:\"go for it\" OR name:[20020101 TO 20030101] NOT title:{Aida TO Carmen} OR title:(+return +\"pink panther\")";

    SolrQueryRequest q = req("q", qstr, "defType", "edismax");
    final SearchComponent c = h.getCore().getSearchComponent("highlightQuery");
    ResponseBuilder rb = new ResponseBuilder(q, new SolrQueryResponse(), Arrays.asList(c));
    rb.doHighlights = true;/*  ww  w  .j  av  a  2 s  . com*/

    c.process(rb);

    assertEquals("+() text:\"go for it\" name:[20020101 TO 20030101] -() (+() +())",
            rb.getHighlightQuery().toString());

}

From source file:com.search.MySearchHandler.java

License:Apache License

@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
    // int sleep = req.getParams().getInt("sleep",0);
    // if (sleep > 0) {log.error("SLEEPING for " + sleep);
    // Thread.sleep(sleep);}

    /*** Pre-processing of the Query by REGEX starts here -------------- ***/
    SolrParams originalParams = req.getOriginalParams();
    SolrParams psuedoParams = req.getParams(); // These psuedoParams keep
    // changing//ww w.  ja va2 s .  c o  m
    if (originalParams.get(CommonParams.Q) != null) {
        String finalQuery;
        String originalQuery = originalParams.get(CommonParams.Q);
        rsp.add("Original query", originalQuery);
        SchemaField keyField = null;
        keyField = req.getCore().getLatestSchema().getUniqueKeyField();
        if (keyField != null) {
            fieldSet.add(keyField.getName());
        }
        /***
         * START CODE TO PARSE QUERY
         * 
         * Arafath's code to prepare query starts here The query should be
         * in the following format ->
         * 
         * 
         * 
         * Example : Original Query:
         * "Which musical object did russ conway play" Temporary Query :
         * "relations:instrument AND entity:enty" // Generate the relation
         * Final Query : "name:"russ conway" AND occupation:musician"
         */
        ParsedQuestion parsedq = new ParsedQuestion();
        parsedq = parseQues(originalQuery);
        if (parsedq != null) {
            System.out.println(parsedq);
            Map<Integer, String> relationstr = getRelation(parsedq.getRelationKeyWord(), parsedq.getWhtype(),
                    req);

            /**
             * END CODE TO PARSE QUERY
             */

            /*** Final Phase starts here ***/
            finalQuery = "title:\"" + parsedq.getSearchName() + "\"";
            NamedList finalparamsList = req.getParams().toNamedList();
            finalparamsList.setVal(finalparamsList.indexOf(CommonParams.Q, 0), finalQuery);
            psuedoParams = SolrParams.toSolrParams(finalparamsList);
            if (psuedoParams.get(CommonParams.SORT) == null) {
                finalparamsList.add(CommonParams.SORT, "score desc");
            } else {
                finalparamsList.setVal(finalparamsList.indexOf(CommonParams.SORT, 0), "score desc");
            }
            int documentsRetrieved = 0;
            if (relationstr != null) {
                rsp.add("total relations retrieved", relationstr.size());
                rsp.add("relations", relationstr);
                NamedList finaldocresults = new NamedList();
                NamedList forwarddocresults = new NamedList();
                Set<String> checkDocuments = new HashSet<String>();

                for (int i = 0; i < relationstr.size() && (documentsRetrieved < 10); i++) {
                    NamedList relationdocresults = new NamedList();
                    String desiredField = relationstr.get(i);
                    Set<String> tempFieldSet = new HashSet<String>();
                    int docsRetrievedforThisRelation = 0;
                    tempFieldSet.add(desiredField);
                    psuedoParams = SolrParams.toSolrParams(finalparamsList);
                    if (psuedoParams.get(CommonParams.FL) == null) {
                        finalparamsList.add(CommonParams.FL, desiredField);
                    } else {
                        finalparamsList.setVal(finalparamsList.indexOf(CommonParams.FL, 0), desiredField);
                    }
                    SolrQueryRequest finalreq = new LocalSolrQueryRequest(req.getCore(), finalparamsList);
                    rsp.add("Final Query", finalreq.getParams().get(CommonParams.Q));

                    SolrQueryResponse finalrsp = new SolrQueryResponse();

                    ResponseBuilder finalrb = new ResponseBuilder(finalreq, finalrsp, components);
                    for (SearchComponent c : components) {
                        c.prepare(finalrb);
                        c.process(finalrb);
                    }

                    DocList finaldocs = finalrb.getResults().docList;
                    if (finaldocs == null || finaldocs.size() == 0) {
                        log.debug("No results");
                        // support for reverse query
                    } else {
                        DocIterator finaliterator = finaldocs.iterator();
                        Document finaldoc;
                        for (int j = 0; j < finaldocs.size(); j++) {
                            try {
                                if (finaliterator.hasNext()) {
                                    int finaldocid = finaliterator.nextDoc();
                                    finaldoc = finalrb.req.getSearcher().doc(finaldocid, tempFieldSet);
                                    if (!checkDocuments.contains(finaldoc.get("id"))) {
                                        if (finaldoc.get(desiredField) != null) {
                                            checkDocuments.add(finaldoc.get("id"));
                                            docsRetrievedforThisRelation++;
                                            documentsRetrieved++;
                                            relationdocresults.add(finaldoc.get("title"), finaldoc);
                                            if (documentsRetrieved >= 10) {
                                                break;
                                            }
                                        }
                                    }
                                }
                            } catch (IOException ex) {
                                java.util.logging.Logger.getLogger(MySearchHandler.class.getName())
                                        .log(Level.SEVERE, null, ex);
                            }
                        }
                        if (docsRetrievedforThisRelation > 0) {
                            rsp.add("docs retrieved for : " + desiredField, docsRetrievedforThisRelation);
                            forwarddocresults.add(desiredField, relationdocresults);
                        }
                    }
                    finalreq.close();
                    if (documentsRetrieved > 0) {
                        rsp.add("type", "forward");
                        rsp.add("final results", forwarddocresults);
                    }
                }
                if (documentsRetrieved == 0) {
                    NamedList reversedocresults = new NamedList();
                    relationstr = getRelationReverse(parsedq.getRelationKeyWord(), req);
                    System.out.println(relationstr);
                    StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_46);
                    String reversequery = "";
                    for (int i = 0; i < relationstr.size(); i++) {
                        QueryParser relationsparser = new QueryParser(Version.LUCENE_46, relationstr.get(i),
                                analyzer);
                        try {
                            reversequery += relationsparser.parse(parsedq.getSearchName()).toString() + " ";
                        } catch (ParseException e) {

                            e.printStackTrace();
                        }
                    }
                    QueryParser relationsparser = new QueryParser(Version.LUCENE_46, "infotype", analyzer);
                    reversequery += relationsparser.parse(parsedq.getWhtype().firstKey().toLowerCase());

                    NamedList reverseList = req.getParams().toNamedList();
                    psuedoParams = SolrParams.toSolrParams(reverseList);
                    reverseList.setVal(reverseList.indexOf(CommonParams.Q, 0), reversequery);
                    SolrQueryRequest reversereq = new LocalSolrQueryRequest(req.getCore(), reverseList);
                    SolrQueryResponse reversersp = new SolrQueryResponse();
                    ResponseBuilder reverserb = new ResponseBuilder(reversereq, reversersp, components);
                    for (SearchComponent c : components) {
                        try {
                            c.prepare(reverserb);
                            c.process(reverserb);
                        } catch (IOException ex) {

                            java.util.logging.Logger.getLogger(MySearchHandler.class.getName())
                                    .log(Level.SEVERE, null, ex);
                        }
                    }
                    DocList reversedocs = reverserb.getResults().docList;
                    if (reversedocs == null || reversedocs.size() == 0) {
                        log.debug("No results");
                        // GET SECOND entry from WHTYPE .. search with that ..
                    } else {
                        //   NamedList docresults = new NamedList();
                        DocIterator reverseiterator = reversedocs.iterator();
                        Document reversedoc;
                        int docScore = 0;
                        for (int m = 0; m < reversedocs.size(); m++) {
                            try {
                                int reversedocid = reverseiterator.nextDoc();
                                reversedoc = reverserb.req.getSearcher().doc(reversedocid, fieldSet);
                                if (reversedoc.get("title") != null) {
                                    documentsRetrieved++;
                                    reversedocresults.add(reversedoc.get("title"), reversedoc);
                                    if (documentsRetrieved >= 10) {
                                        break;
                                    }
                                }
                            } catch (IOException ex) {
                                java.util.logging.Logger.getLogger(MySearchHandler.class.getName())
                                        .log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                    if (documentsRetrieved == 0) {
                        rsp.add("message", "No Results found. Try another query!");
                    } else {
                        rsp.add("type", "reverse");
                        rsp.add("final results", reversedocresults);
                    }
                    reversereq.close();
                }
            } else {
                if (documentsRetrieved == 0) {
                    rsp.add("message", "No Results found. Please rephrase the query!");
                }
            }
        } else {
            rsp.add("message", "This is not a valid query!");
        }
    } else {
        rsp.add("message", "User should provide at least one word as a query!");
    }
}

From source file:com.search.MySearchHandler.java

License:Apache License

private Map<Integer, String> getRelationReverse(String value, SolrQueryRequest req) {
    /*** Galla's modified code starts here ---- >
     * /*from   w w w .j  a  v a 2  s . c om*/
     */
    StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_46);
    QueryParser relationsparser = new QueryParser(Version.LUCENE_46, "relations", analyzer);
    QueryParser entityparser = new QueryParser(Version.LUCENE_46, "entity", analyzer);
    QueryParser fieldidparser = new QueryParser(Version.LUCENE_46, "fieldid", analyzer);

    Map<Integer, String> desiredFieldList = null;
    int desiredFieldsCount = 0;
    String desiredRelation = null;

    Set<String> checkRelation = null;
    if (desiredFieldsCount < 5) {
        desiredFieldList = new HashMap<Integer, String>();
        checkRelation = new HashSet<String>();
        NamedList tempparamsList = req.getParams().toNamedList();
        SolrParams psuedoParams = SolrParams.toSolrParams(tempparamsList);
        if (psuedoParams.get(CommonParams.SORT) == null) {
            tempparamsList.add(CommonParams.SORT, "score desc");
        } else {
            tempparamsList.setVal(tempparamsList.indexOf(CommonParams.SORT, 0), "score desc");
        }
        SolrQueryRequest firstreq = null;
        SolrQueryResponse firstrsp = null;
        ResponseBuilder firstrb = null;
        DocList docs = null;

        String relString = "";
        String fieldString = "";
        try {
            relString = relationsparser.parse(value).toString();

            fieldString = fieldidparser.parse(value).toString();
        } catch (ParseException e) {

            e.printStackTrace();
        }
        //      (+relations:"children" and +entity:"num") or (relations:"children" and fieldid:"children") or (fieldid:"children" and entity:"num")
        String tempQuery = "(" + relString + ")" + " OR (" + fieldString + ")";

        System.out.println(tempQuery);
        tempparamsList.setVal(tempparamsList.indexOf(CommonParams.Q, 0), tempQuery);

        firstreq = new LocalSolrQueryRequest(req.getCore(), tempparamsList);
        firstrsp = new SolrQueryResponse();
        firstrb = new ResponseBuilder(firstreq, firstrsp, components);

        for (SearchComponent c : components) {
            try {
                c.prepare(firstrb);
                c.process(firstrb);
            } catch (IOException ex) {

                java.util.logging.Logger.getLogger(MySearchHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        docs = firstrb.getResults().docList;

        if (docs == null || docs.size() == 0) {
            log.debug("No results");
            // GET SECOND entry from WHTYPE .. search with that ..

        } else {
            //   NamedList docresults = new NamedList();
            DocIterator iterator = docs.iterator();
            Document doc;
            int docScore = 0;
            for (int i = 0; i < docs.size(); i++) {
                try {
                    int docid = iterator.nextDoc();
                    doc = firstrb.req.getSearcher().doc(docid, fieldSet);
                    desiredRelation = doc.get("fieldid");
                    if (!checkRelation.contains(desiredRelation)) {
                        checkRelation.add(desiredRelation);
                        desiredFieldList.put(desiredFieldsCount++, desiredRelation);
                        System.out.println("vgalla's relation : " + desiredRelation);
                        if (desiredFieldsCount >= 5) {
                            return desiredFieldList;
                        }
                    }
                } catch (IOException ex) {
                    java.util.logging.Logger.getLogger(MySearchHandler.class.getName()).log(Level.SEVERE, null,
                            ex);
                }
            }
        }
        firstreq.close();

        /*** Galla's code ends here ----- >
         * 
         */
    }

    return desiredFieldList;
}

From source file:com.search.MySearchHandler.java

License:Apache License

private static Map<Integer, String> getRelation(String value, TreeMap<String, Double> whtype,
        SolrQueryRequest req) {//from w w  w.  j a  v  a  2s  .  com

    /***
     * Galla's modified code starts here ---- >
     * 
     */
    Map<Integer, String> desiredFieldList = null;
    if (whtype != null) {
        StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_46);
        QueryParser relationsparser = new QueryParser(Version.LUCENE_46, "relations", analyzer);
        QueryParser entityparser = new QueryParser(Version.LUCENE_46, "entity", analyzer);
        QueryParser fieldidparser = new QueryParser(Version.LUCENE_46, "fieldid", analyzer);

        int desiredFieldsCount = 0;
        String desiredRelation = null;
        Set<String> whtypeSet = whtype.keySet();
        Set<String> checkRelation = null;
        if (!whtypeSet.isEmpty() && (desiredFieldsCount < 5)) {
            desiredFieldList = new HashMap<Integer, String>();
            checkRelation = new HashSet<String>();
            NamedList tempparamsList = req.getParams().toNamedList();
            SolrParams psuedoParams = SolrParams.toSolrParams(tempparamsList);
            if (psuedoParams.get(CommonParams.SORT) == null) {
                tempparamsList.add(CommonParams.SORT, "score desc");
            } else {
                tempparamsList.setVal(tempparamsList.indexOf(CommonParams.SORT, 0), "score desc");
            }
            SolrQueryRequest firstreq = null;
            SolrQueryResponse firstrsp = null;
            ResponseBuilder firstrb = null;
            DocList docs = null;
            for (String tempStr : whtypeSet) {
                String tempType = tempStr.toLowerCase().trim();
                String relString = "";
                String entyString = "";
                String fieldString = "";
                try {
                    relString = relationsparser.parse(value).toString();
                    entyString = entityparser.parse(tempType).toString();
                    fieldString = fieldidparser.parse(value).toString();
                } catch (ParseException e) {

                    e.printStackTrace();
                }
                // (+relations:"children" and +entity:"num") or
                // (relations:"children" and fieldid:"children") or
                // (fieldid:"children" and entity:"num")
                String tempQuery = "(" + relString + " AND " + entyString + ")" + " OR " + "(" + relString
                        + " AND " + fieldString + ")" + " OR " + "(" + fieldString + " AND " + entyString + ")";

                System.out.println(tempQuery);
                tempparamsList.setVal(tempparamsList.indexOf(CommonParams.Q, 0), tempQuery);

                firstreq = new LocalSolrQueryRequest(req.getCore(), tempparamsList);
                firstrsp = new SolrQueryResponse();
                firstrb = new ResponseBuilder(firstreq, firstrsp, components);

                for (SearchComponent c : components) {
                    try {
                        c.prepare(firstrb);
                        c.process(firstrb);
                    } catch (IOException ex) {

                        java.util.logging.Logger.getLogger(MySearchHandler.class.getName()).log(Level.SEVERE,
                                null, ex);
                    }
                }

                docs = firstrb.getResults().docList;

                if (docs == null || docs.size() == 0) {
                    log.debug("No results");
                    // GET SECOND entry from WHTYPE .. search with that ..

                } else {
                    // NamedList docresults = new NamedList();
                    DocIterator iterator = docs.iterator();
                    Document doc;
                    int docScore = 0;
                    for (int i = 0; i < docs.size(); i++) {
                        try {
                            int docid = iterator.nextDoc();
                            doc = firstrb.req.getSearcher().doc(docid, fieldSet);
                            desiredRelation = doc.get("fieldid");
                            if (!checkRelation.contains(desiredRelation)) {
                                checkRelation.add(desiredRelation);
                                desiredFieldList.put(desiredFieldsCount++, desiredRelation);
                                System.out.println("vgalla's relation : " + desiredRelation);
                                if (desiredFieldsCount >= 5) {
                                    return desiredFieldList;
                                }
                            }
                        } catch (IOException ex) {
                            java.util.logging.Logger.getLogger(MySearchHandler.class.getName())
                                    .log(Level.SEVERE, null, ex);
                        }
                    }
                }
                firstreq.close();

                /***
                 * Galla's code ends here ----- >
                 * 
                 */

                String exrelstring = "";

                String[] strarray = value.split(" ");

                for (int i = 0; i < strarray.length; i++) {
                    if (exrelmap.containsKey(strarray[i].toLowerCase().trim())) {
                        exrelstring += exrelmap.get(strarray[i].toLowerCase().trim());
                    }
                }

                if (!exrelstring.equals("")) {
                    String[] temp = exrelstring.split("~~");
                    for (int i = 0; i < temp.length; i++) {
                        if (!temp[i].trim().equals("")) {

                            String mapdetect = mappingmap.get(temp[i].trim());

                            if (mapdetect.toLowerCase().trim().equals(tempType)) {
                                desiredRelation = temp[i].trim();
                                if (!checkRelation.contains(desiredRelation)) {
                                    checkRelation.add(desiredRelation);
                                    desiredFieldList.put(desiredFieldsCount++, desiredRelation);
                                    System.out.println("arafath's relation : " + desiredRelation);
                                    if (desiredFieldsCount >= 5) {
                                        return desiredFieldList;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return desiredFieldList;
}