Example usage for org.apache.solr.client.solrj SolrQuery setQuery

List of usage examples for org.apache.solr.client.solrj SolrQuery setQuery

Introduction

In this page you can find the example usage for org.apache.solr.client.solrj SolrQuery setQuery.

Prototype

public SolrQuery setQuery(String query) 

Source Link

Usage

From source file:edu.indiana.htrc.action.solrproxylog.SolrProxyGeneralAction.java

License:Apache License

public String execute() {

    setErrorPage("/pages/SolrProxy.jsp");
    if (!Utility.validateInputDateOrder(from, to)) {
        return ERROR;
    }//from  w  w  w . j av  a  2  s .  c o m

    setDisplay("/pages/solrProxyAllResult.jsp");

    String input_start_UTC = Utility.convertDate2UTC(from);
    String input_end_UTC = Utility.convertDate2UTC(to);

    Solr4Connector connector = new Solr4Connector();
    SolrServer solr_server = connector.connect();

    SolrQuery query = new SolrQuery();
    String queryStr = "timeStamp:[" + input_start_UTC + " TO " + input_end_UTC + "]"; // " AND " + "userName:" + userName;

    if (sourceIP != null) {
        queryStr = queryStr + " AND " + "sourceIP:" + sourceIP;
    }
    if (XForward_For != null) {
        queryStr = queryStr + " AND " + "XForward_For:" + XForward_For;
    }

    queryStr = queryStr + " AND " + "logName:" + "SOLR-PROXY-Log";
    query.setQuery(queryStr).setRows(0).setFacet(true).set("facet.mincount", 1).set("facet.limit", 18)
            .set("facet.sort", "count").set("facet.date", "timeStamp")
            .set("f.timeStamp.facet.date.start", input_start_UTC)
            .set("f.timeStamp.facet.date.end", input_end_UTC).set("f.timeStamp.facet.date.gap", "+1DAY")
            .set("f.timeStamp.facet.mincount", 0).set("facet.field", fieldName);

    QueryResponse query_response = null;

    try {
        // logger.debug("solr_server == null is " + solr_server == null);
        query_response = solr_server.query(query);

    } catch (SolrServerException e) {
        // logger.debug("solr_server == null is " + solr_server == null);
        e.printStackTrace();
    }

    // ///////////////////generate charts/////////////////////////////////////////
    List<FacetField> facet_field_list = query_response.getFacetFields();

    for (int i = 0; i < facet_field_list.size(); i++) {

        FacetField facet_field = facet_field_list.get(i);
        String field_name = facet_field.getName();

        Map<String, Integer> map = Utility.getFacetFieldAsMap(facet_field);

        if (field_name.equals("date")) {
            FacetField facet_date = query_response.getFacetDate("timeStamp");

            Map<String, Integer> UTC_detail_time_map = Utility.getFacetFieldAsMap(facet_date);
            Map<String, Integer> UTC_YMD_map = Utility.convertMapFromUTCDetail2UTCYMD(UTC_detail_time_map);

            setTimeIntervalMap(UTC_YMD_map);
            //setDateMap(map);
        } else if (field_name.equals("sourceIP")) {
            setIpMap(map);
        } else if (field_name.equals("responseStatus")) {
            setResponseStatusMap(map);
        } else if (field_name.equals("XForward_For")) {
            setXForward_ForMap(map);
        }
    }
    connector.disconnect();
    return SUCCESS;
}

From source file:edu.jhu.cvrg.ceptools.main.PubMedSearch.java

License:Apache License

public void SearchSolr(int mypmid) {

    int currpmid = mypmid;

    try {//ww w .  j  a v a  2s . c  om

        CoreAdminRequest adminRequest = new CoreAdminRequest();
        adminRequest.setAction(CoreAdminAction.RELOAD);

        SolrServer solr = new HttpSolrServer("http://localhost:8983/solr");
        String query;
        query = "pmid:" + currpmid;
        SolrQuery theq = new SolrQuery();
        theq.setQuery(query);

        QueryResponse response = new QueryResponse();
        response = solr.query(theq, org.apache.solr.client.solrj.SolrRequest.METHOD.POST);
        SolrDocumentList list = response.getResults();

        for (SolrDocument doc : list) {
            Publication currlist = new Publication();
            currlist.setTitle(doc.getFieldValue("ptitle").toString());
            currlist.setAbstract(doc.getFieldValue("abstract").toString());
            currlist.setPmid(Integer.valueOf(doc.getFieldValue("pmid").toString()));

            results.add(currlist);

        }

    } catch (Exception ex) {
        logger.info(ex);
        StringWriter stack = new StringWriter();
        ex.printStackTrace(new PrintWriter(stack));

    }
}

From source file:edu.jhu.cvrg.ceptools.main.PubMedSearch.java

License:Apache License

public void SearchSolrList(List<Integer> mypmids) {

    String querylist = "pmid:(";
    List<Publication> results2 = new ArrayList<Publication>();

    for (Integer currint : mypmids) {
        querylist += currint + " OR ";

    }//from  w ww  . j  ava2 s .com

    if (querylist.length() > 5) {
        querylist = querylist.substring(0, querylist.length() - 4);
        querylist += ")";
    }

    try {

        CoreAdminRequest adminRequest = new CoreAdminRequest();
        adminRequest.setAction(CoreAdminAction.RELOAD);

        SolrServer solr = new HttpSolrServer("http://localhost:8983/solr");
        SolrQuery theq = new SolrQuery();
        theq.setQuery(querylist);
        QueryResponse response = new QueryResponse();

        response = solr.query(theq, org.apache.solr.client.solrj.SolrRequest.METHOD.POST);
        SolrDocumentList list = response.getResults();

        for (SolrDocument doc : list) {
            Publication currlist = new Publication();
            solrindex = 0;
            currlist.setTitle(doc.getFieldValue("ptitle").toString());
            currlist.setAbstract(doc.getFieldValue("abstract").toString());
            currlist.setPmid(Integer.valueOf(doc.getFieldValue("pmid").toString()));
            currlist.setCompleted(Boolean.valueOf(doc.getFieldValue("completion").toString()));
            if (doc.getFieldValue("lruid") != null) {
                currlist.setUserid(Integer.valueOf(doc.getFieldValue("lruid").toString()));
            } else {
                currlist.setUserid(0);
            }
            if (doc.getFieldValues("pfileinfo") != null) {

                Collection<Object> currcoll = doc.getFieldValues("pfileinfo");

                for (Object currobj : currcoll) {
                    currlist = convertStore(String.valueOf(currobj), currlist);
                }

            }

            results2.add(currlist);

        }

        int currcounter = 0;
        for (Publication solrmatch : results2) {
            currcounter = 0;
            for (Publication publistrecord : publications) {
                if (solrmatch.getPmid() == publistrecord.getPmid()) {

                    publications.get(currcounter).setExists(true);
                    publications.get(currcounter).setCompleted(solrmatch.getCompleted());
                    publications.get(currcounter).setFstorefiles(solrmatch.getFstorefiles());
                    publications.get(currcounter).setUserid(solrmatch.getUserid());

                }
                currcounter++;
            }

        }

    } catch (Exception ex) {
        logger.error("Error : ", ex);

    }
}

From source file:edu.jhu.cvrg.ceptools.main.SearchPubs.java

License:Apache License

@SuppressWarnings("unchecked")
public void SearchSolr() {

    try {/*from   www .  j a va2  s  .c o  m*/

        // CoreAdminRequest adminRequest = new CoreAdminRequest();
        // adminRequest.setAction(CoreAdminAction.RELOAD);

        SolrServer solr = new HttpSolrServer("http://localhost:8983/solr");
        String query;
        query = "collector:" + searchentry;

        SolrQuery theq = new SolrQuery();
        theq.setQuery(query);
        theq.setRows(1000);

        QueryResponse response = new QueryResponse();
        response = solr.query(theq);
        SolrDocumentList list = response.getResults();

        int docnum = 1;

        for (SolrDocument doc : list) {
            Publication currlist = new Publication();

            List<String> fullnames = new ArrayList<String>();
            String currepubsum1 = "", currepubsum2 = "";

            currlist.setTitle(doc.getFieldValue("ptitle").toString());

            currlist.setAbstract(doc.getFieldValue("abstract").toString());
            currlist.setPmid(Integer.valueOf(doc.getFieldValue("pmid").toString()));

            pmid = String.valueOf(currlist.getPmid());

            if (doc.getFieldValue("lruid") != null) {
                currlist.setUserid(doc.getFieldValue("lruid").toString());
            } else {
                currlist.setUserid("");
            }

            if (doc.getFieldValue("journalname") != null) {
                currlist.setJournalname(doc.getFieldValue("journalname").toString());
            }
            if (doc.getFieldValue("completion") != null) {
                currlist.setCompleted(Boolean.valueOf(doc.getFieldValue("completion").toString()));
            } else {
                currlist.setCompleted(false);
            }
            if (doc.getFieldValue("journalyear") != null) {
                currlist.setJournalyear(doc.getFieldValue("journalyear").toString());
            }
            if (doc.getFieldValue("journalday") != null) {
                currlist.setJournalday(doc.getFieldValue("journalday").toString());
            }
            if (doc.getFieldValue("journalmonth") != null) {
                currlist.setJournalmonth(doc.getFieldValue("journalmonth").toString());
            }
            if (doc.getFieldValue("journalpage") != null) {
                currlist.setJournalstartpg(doc.getFieldValue("journalpage").toString());
            }
            if (doc.getFieldValue("journalissue") != null) {
                currlist.setJournalissue(doc.getFieldValue("journalissue").toString());
            }
            if (doc.getFieldValue("journalvolume") != null) {
                currlist.setJournalvolume(doc.getFieldValue("journalvolume").toString());
            }
            if (doc.getFieldValue("publication_year") != null) {
                currlist.setYear(doc.getFieldValue("publicationdate_year").toString());
            }
            if (doc.getFieldValue("doi") != null) {
                currlist.setDoi(doc.getFieldValue("doi").toString());
            }

            if (doc.getFieldValues("pfileinfo") != null) {

                Collection<Object> currcoll = doc.getFieldValues("pfileinfo");

                for (Object currobj : currcoll) {
                    convertStore(String.valueOf(currobj), currlist);
                }

            }

            List<String> fieldValue = (List<String>) doc.getFieldValue("author_firstname");
            currlist.setFauthors(fieldValue);
            currlist.setLauthors((List<String>) doc.getFieldValue("author_lastname"));

            if (doc.getFieldValue("epubmonth") != null) {
                currlist.setEpubmonth(doc.getFieldValue("epubmonth").toString());
            }

            if (doc.getFieldValue("epubyear") != null) {
                currlist.setEpubyear(doc.getFieldValue("epubyear").toString());
            }
            if (doc.getFieldValue("epubday") != null) {
                currlist.setEpubday(doc.getFieldValue("epubday").toString());
            }
            if (doc.getFieldValue("author_fullname_list") != null) {

                currlist.setAuthorfull(doc.getFieldValue("author_fullname_list").toString());
            }

            int counter = 0;

            for (String currstring : currlist.getFauthors()) {
                currstring += " " + currlist.getLauthors().get(counter);
                fullnames.add(currstring);
                counter++;
            }

            currlist.setFullnames(fullnames);

            if (currlist.getJournalvolume().length() > 0) {
                currepubsum2 += currlist.getJournalvolume();
            }

            if (currlist.getJournalissue().length() > 0) {
                currepubsum2 += "(" + currlist.getJournalissue() + ")" + ":";
            }

            if (currlist.getJournalstartpg().length() > 0) {
                currepubsum2 += currlist.getJournalstartpg() + ".";
            }

            if (currlist.getEpubday().length() < 1 && currlist.getEpubmonth().length() < 1
                    && currlist.getEpubyear().length() < 1) {
                currepubsum1 = "[Epub ahead of print]";
            } else if (currlist.getEpubyear().length() > 0) {
                currepubsum1 = "Epub " + currlist.getEpubyear() + " " + currlist.getEpubmonth() + " "
                        + currlist.getEpubday();
            } else {
                currepubsum1 = "";
            }

            currlist.setEpubsum(currepubsum1);
            currlist.setEpubsum2(currepubsum2);
            currlist.setIndex(docnum);

            results.add(currlist);
            docnum++;
        }

    } catch (Exception ex) {
        logger.info(ex);
        StringWriter stack = new StringWriter();
        ex.printStackTrace(new PrintWriter(stack));

    }
}

From source file:edu.ku.brc.sgr.MatchableIndexedId.java

License:Open Source License

@Override
public MatchResults doMatch(SolrServer server, SolrQuery baseQuery) {
    final SolrQuery query = baseQuery.getCopy();
    query.setQuery("id:" + id);

    final QueryResponse resp;
    try {//from   ww  w .ja  v  a 2s  . c om
        resp = server.query(query);
    } catch (SolrServerException e) {
        // TODO Auto-generated catch block
        throw new RuntimeException(e);
    }

    final SolrDocumentList docs = resp.getResults();
    final float maxScore = (docs != null) ? docs.getMaxScore() : 0.0f;
    final ImmutableList.Builder<Match> msBuilder = ImmutableList.builder();
    if (docs != null) {
        for (SolrDocument doc : docs) {
            float score = (Float) doc.getFieldValue("score");
            SGRRecord match = SGRRecord.fromSolrDocument(doc);
            msBuilder.add(new Match(match, score));
        }
    }
    return new MatchResults(id, resp.getQTime(), maxScore, msBuilder.build());
}

From source file:edu.ub.ir.oof1.service.Solr.java

/**
 * Used only for searching a single news article
 *
 * @param _query//from ww  w  . j a  va2s. com
 * @param resultType
 * @return
 */
@Override
public List<AbstractModel> query(String _query, Class<? extends AbstractModel> resultType) {
    List<AbstractModel> out = new ArrayList<AbstractModel>();

    SolrQuery query = new SolrQuery();
    query.setQuery(_query);
    query.setRequestHandler(Properties.SOLR_QUERY_HANDLER);

    try {
        QueryResponse response = SERVER.query(query);
        SolrDocumentList docs = response.getResults();
        for (SolrDocument doc : docs) {
            AbstractModel model = null;

            String news_id = (String) doc.getFieldValue("news_id");
            //System.out.println("news_id : " + news_id);
            //System.out.println("highlighting : " + response.getHighlighting().get(news_id));
            if (news_id != null && response.getHighlighting().get(news_id) != null) {
                model = getModelForSolrDoc(doc, resultType, response.getHighlighting().get(news_id));
            } else {
                model = getModelForSolrDoc(doc, resultType);
            }

            out.add(model);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return out;
}

From source file:edu.ub.ir.oof1.service.Solr.java

/**
 * Used only for searching a single news article
 *
 * @param _query//from  w  ww .  ja  v a 2 s .c  om
 * @return
 */
public Suggestions getAutoSuggest(String _query) {
    Suggestions out = new Suggestions();
    List<String> suggs = new ArrayList<String>();
    System.out.println("Solr query : " + _query);
    SolrQuery query = new SolrQuery();
    query.setQuery(_query);
    query.setRequestHandler(Properties.SOLR_AUTO_SUGGEST_HANDLER);

    try {
        QueryResponse response = SERVER.query(query);
        suggs = spellcheck(response);
        System.out.println("Solr sugg : " + suggs);
        out.setSuggestions(suggs);
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("Final Solr: " + out);
    return out;
}

From source file:edu.ub.ir.oof1.service.Solr.java

/**
 * Used for searching multiple news articles
 *
 * @param _query//from ww w  .  j  a  v a  2s. c  om
 * @param resultType
 * @param _user_id
 * @return
 */
@Override
public NewsResults query(String _query, Class<? extends AbstractModel> resultType, String _user_id) {

    List<News> out = new ArrayList<News>();
    List<String> spellCheck = new ArrayList<String>();

    boolean queryBack = false;

    SolrQuery query = new SolrQuery();
    query.setQuery(_query + " AND " + _user_id);
    query.setRequestHandler(Properties.SOLR_QUERY_HANDLER);

    try {
        QueryResponse response = SERVER.query(query);
        SolrDocumentList docs = response.getResults();
        System.out.println("***Before queryBack***");
        queryBack = queryConstruct(docs, out, _user_id, response, resultType);

        if (queryBack) {
            System.out.println("Entered queryback");
            query = new SolrQuery();
            query.setQuery(_query + " NOT " + _user_id);
            query.setRequestHandler(Properties.SOLR_QUERY_HANDLER);

            response = SERVER.query(query);
            docs = response.getResults();
            queryBack = queryConstruct(docs, out, _user_id, response, resultType);

            if (queryBack) {
                query = new SolrQuery();
                query.setQuery(_query);
                query.setRequestHandler("/spellcheck");

                response = SERVER.query(query);
                spellCheck = spellcheck(response);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return new NewsResults(out, spellCheck);
}

From source file:edu.ub.ir.oof1.service.Solr.java

public void updateDocClick(String _user_id, String _news_id) {
    try {//  www . j a  v  a 2s.  c  o m

        SolrInputDocument updateDoc = new SolrInputDocument();
        SolrQuery query = new SolrQuery();
        query.setQuery("news_id:" + _news_id);
        query.setRequestHandler(Properties.SOLR_QUERY_HANDLER);

        QueryResponse response = SERVER.query(query);
        SolrDocumentList docs = response.getResults();
        if (docs == null) {
            return;
        }
        if (docs.size() < 1) {
            return;
        }
        for (String attribute : docs.get(0).getFieldNames()) {
            //Retain all the records except userCount and Count
            if (!attribute.equals("user_count") && !attribute.equals("count") && !attribute.equals("score")
                    && !attribute.equals("_version_")) {
                updateDoc.addField(attribute, docs.get(0).getFieldValue(attribute));
            } else if (attribute.equals("user_count")) {
                List<String> userCount = (List<String>) docs.get(0).getFieldValue("user_count");
                List<String> updatedCount = new ArrayList<String>();
                boolean userFound = false;

                if (userCount != null && userCount.size() > 0) {
                    for (String user : userCount) {
                        String[] buffer = user.split(":");
                        if (buffer.length > 1) {
                            if (buffer[0].equals(_user_id)) {
                                int count = Integer.parseInt(buffer[1]);
                                updatedCount.add(buffer[0] + ":" + ++count);
                                userFound = true;
                            } else {
                                //This is not the user who read this article at the moment
                                updatedCount.add(user);
                            }
                        } else {
                            //Means this user is reading this article for the first time or
                            //This is the first time any user is reading this article
                            userFound = true;
                            updatedCount.add(_user_id + ":" + 1);
                        }
                    }

                    if (userFound == false) //Means this user is reading this article for the first time
                    {
                        updatedCount.add(_user_id + ":" + 1);
                    }
                } else {
                    //This logic will not happen in real time. Added for worst-case scenario
                    updatedCount.add(_user_id + ":" + 1);
                }

                updateDoc.addField("user_count", updatedCount);
            } else if (attribute.equals("count")) {
                //Increment the global count for this article.
                //Used to track the most viewed articles irrespective of the user
                Map<String, Integer> countIncMap = new HashMap<String, Integer>(1);
                countIncMap.put("inc", 1);

                updateDoc.addField("count", countIncMap);
            }
        }
        SERVER.add(updateDoc);
        SERVER.commit();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.unc.lib.dl.cdr.services.rest.ContainerDataFileChecksumsController.java

License:Apache License

@RequestMapping(value = "/edit/fileinfo/{pid}")
public void get(@PathVariable("pid") String pid, HttpServletResponse response)
        throws SolrServerException, IOException {
    String fid = pid.replace(":", "_");
    response.addHeader("Content-Disposition", "attachment; filename=\"" + fid + "-fileinfo.csv\"");
    try (ServletOutputStream out = response.getOutputStream()) {
        out.print("title");
        out.print(',');
        out.print("pid");
        out.print(',');
        out.print("mimetype");
        out.print(',');
        out.print("length");
        out.print(',');
        out.println("checksum");

        if (server == null)
            initializeSolrServer();//  w  w  w . j a v a 2  s .com
        SolrQuery parameters = new SolrQuery();
        parameters.setQuery("contentModel:" + ClientUtils.escapeQueryChars("info:fedora/cdr-model:Simple")
                + " ancestorPath:*" + ClientUtils.escapeQueryChars("," + pid + ",") + "*");
        parameters.addSort("filesizeTotal", ORDER.desc);
        parameters.addField("title");
        parameters.addField("id");
        parameters.addField("datastream");
        QueryResponse solrResponse = server.query(parameters);

        for (SolrDocument doc : solrResponse.getResults()) {
            Map<String, String> line = new HashMap<String, String>();
            line.put("pid", (String) doc.getFieldValue("id"));
            line.put("title", (String) doc.getFieldValue("title"));
            String[] dsValues = new String[5];
            for (Object ds : doc.getFieldValues("datastream")) {
                String dstr = (String) ds;
                if (dstr.startsWith("DATA_FILE|")) {
                    dsValues = dstr.split(Pattern.quote("|"));
                    break;
                }
            }
            line.put("md5sum", dsValues[4]);
            line.put("length", dsValues[3]);
            line.put("mimetype", dsValues[1]);
            outputCSV(line, out);
        }
    }
}