Example usage for org.apache.lucene.search BooleanQuery BooleanQuery

List of usage examples for org.apache.lucene.search BooleanQuery BooleanQuery

Introduction

In this page you can find the example usage for org.apache.lucene.search BooleanQuery BooleanQuery.

Prototype

BooleanQuery

Source Link

Usage

From source file:axiom.scripting.rhino.LuceneQueryDispatcher.java

License:Open Source License

public Scriptable getReferences(ArrayList sources, ArrayList targets, final int mode) throws Exception {
    long start = System.currentTimeMillis();
    final GlobalObject global = this.core != null ? this.core.global : null;
    final Application app = this.app;

    final String ID_FIELD = LuceneManager.ID;
    final String REF_LIST = LuceneManager.REF_LIST_FIELD;
    final BooleanClause.Occur SHOULD = BooleanClause.Occur.SHOULD;
    final BooleanClause.Occur MUST = BooleanClause.Occur.MUST;

    final int sources_size = sources.size();
    final int targets_size = targets.size();

    ArrayList results = new ArrayList();

    BooleanQuery sub_query = new BooleanQuery();
    for (int i = 0; i < sources_size; i++) {
        sub_query.add(new TermQuery(new Term(ID_FIELD, sources.get(i).toString())), SHOULD);
    }//from   www.  j  av a  2  s.co  m

    BooleanQuery primary = new BooleanQuery();
    primary.add(sub_query, MUST);

    sub_query = new BooleanQuery();
    for (int i = 0; i < targets_size; i++) {
        sub_query.add(new TermQuery(new Term(REF_LIST, targets.get(i).toString())), SHOULD);
    }
    primary.add(sub_query, MUST);

    IndexSearcher searcher = null;

    try {
        if (app.debug()) {
            app.logEvent("running query " + primary);
        }
        searcher = this.lmgr.getIndexSearcher();
        Hits hits = searcher.search(primary);

        HashSet target_set = new HashSet(targets);
        luceneResultsToReferences(hits, results, target_set, mode);
    } catch (Exception ex) {
        results.clear();
        app.logError(ErrorReporter.errorMsg(this.getClass(), "getReferences") + "Occured on query = " + primary,
                ex);
    } finally {
        this.lmgr.releaseIndexSearcher(searcher);
    }

    if (app.debug()) {
        long time = System.currentTimeMillis() - start;
        app.logEvent("... took " + (time / 1000.0) + " seconds\n ------");
    }

    return Context.getCurrentContext().newArray(global, results.toArray());
}

From source file:axiom.scripting.rhino.LuceneQueryDispatcher.java

License:Open Source License

public Object getDirectionalNodesFor(Object o, int direction, Object prototypes, Object filter, Object options)
        throws Exception {
    final GlobalObject global = this.core != null ? this.core.global : null;
    final Application app = this.app;
    final LuceneManager lmgr = this.lmgr;
    INode node = null;/*from ww  w.  j av a 2 s.co  m*/

    int objLayer = -1;
    ArrayList objects = null;
    if (o instanceof AxiomObject) {
        objects = new ArrayList();
        node = ((AxiomObject) o).node;
        if (node != null) {
            objects.add(node.getID());
            if (node instanceof Node) {
                objLayer = ((Node) node).getLayer();
            }
        }
    } else if (o instanceof INode) {
        objects = new ArrayList();
        node = (INode) o;
        objects.add(node.getID());
        if (node instanceof Node) {
            objLayer = ((Node) node).getLayer();
        }
    } else if (o instanceof String) {
        objects = this.getNodesByPath((String) o);
    }

    final int size = objects == null ? 0 : objects.size();
    if (size == 0) {
        if (global != null) {
            return Context.getCurrentContext().newArray(global, new Object[0]);
        } else {
            return new Object[0];
        }
    }

    int _layer = getLayer(options);

    final int mode;
    if (_layer > -1) {
        mode = _layer;
    } else if (objLayer > -1) {
        mode = objLayer;
    } else {
        RequestEvaluator req_eval = app.getCurrentRequestEvaluator();
        if (req_eval != null) {
            mode = req_eval.getLayer();
        } else {
            mode = DbKey.LIVE_LAYER;
        }
    }

    int maxResults = Integer.MAX_VALUE;
    try {
        maxResults = getMaxResults(options);
    } catch (Exception e) {
        maxResults = Integer.MAX_VALUE;
    }
    if (maxResults < 0) {
        maxResults = Integer.MAX_VALUE;
    }

    ArrayList protos = new ArrayList();
    if (prototypes != null && prototypes != Scriptable.NOT_FOUND) {
        QueryBean.setPrototypeArrays(this.app, prototypes, protos, new ArrayList(),
                new HashMap<String, ArrayList>());
    }

    IFilter theFilter = QueryBean.getFilterFromObject(filter);
    BooleanQuery primary = new BooleanQuery();
    ResourceProperties props = QueryBean.getResourceProperties(this.app, protos);
    parseFilterIntoQuery(theFilter, primary, props);

    NodeManager nmgr = app.getNodeManager();
    ArrayList node_list = new ArrayList();
    HashSet encountered_keys = new HashSet();
    int list_count = 0;

    for (int i = 0; i < size; i++) {
        if (node_list.size() >= maxResults) {
            break;
        }

        Key[] node_keys = null;
        try {
            node_keys = (direction == 0
                    ? lmgr.getTargetNodeIds(objects.get(i).toString(), mode, protos, primary,
                            getLuceneSort(getSortObject(options)))
                    : lmgr.getSourceNodeIds(objects.get(i).toString(), mode, protos, primary,
                            getLuceneSort(getSortObject(options))));
        } catch (Exception ex) {
            node_keys = null;
            app.logError(ErrorReporter.errorMsg(this.getClass(), "getDirectionalNodesFor")
                    + "Could not retrieve " + (direction == 0 ? "target" : "source") + " nodes", ex);
        }

        if (node_keys == null) {
            continue;
        }

        int length = node_keys.length;
        for (int j = 0; j < length; j++) {
            if (encountered_keys.contains(node_keys[j])) {
                continue;
            }

            Node curr = null;
            try {
                curr = nmgr.getNode(node_keys[j]);
            } catch (Exception ex) {
                curr = null;
                app.logError(ErrorReporter.errorMsg(this.getClass(), "getDirectionalNodesFor")
                        + "Could not get node '" + node_keys[j].getID() + "'.", ex);
            }

            if (curr != null) {
                if (global != null) {
                    node_list.add(Context.toObject(curr, global));
                } else {
                    node_list.add(curr);
                }
                if (node_list.size() >= maxResults) {
                    break;
                }
                encountered_keys.add(node_keys[j]);
            }
        }
    }

    if (global != null) {
        return Context.getCurrentContext().newArray(core.global, node_list.toArray());
    } else {
        return node_list.toArray();
    }
}

From source file:axiom.scripting.rhino.LuceneQueryDispatcher.java

License:Open Source License

public int getDirectionalNodesForCount(Object o, int direction, Object prototypes, Object filter,
        Object options) throws Exception {
    final Application app = this.app;
    final LuceneManager lmgr = this.lmgr;
    INode node = null;//from   w  ww .  ja v  a 2 s .  co m

    int objLayer = -1;
    ArrayList objects = null;
    if (o instanceof AxiomObject) {
        objects = new ArrayList();
        node = ((AxiomObject) o).node;
        if (node != null) {
            objects.add(node.getID());
            if (node instanceof Node) {
                objLayer = ((Node) node).getLayer();
            }
        }
    } else if (o instanceof INode) {
        objects = new ArrayList();
        node = (INode) o;
        objects.add(node.getID());
        if (node instanceof Node) {
            objLayer = ((Node) node).getLayer();
        }
    } else if (o instanceof String) {
        objects = this.getNodesByPath((String) o);
    }

    final int size = objects == null ? 0 : objects.size();
    if (size == 0) {
        return 0;
    }

    int _layer = getLayer((Scriptable) options);

    final int mode;
    if (_layer > -1) {
        mode = _layer;
    } else if (objLayer > -1) {
        mode = objLayer;
    } else {
        RequestEvaluator req_eval = app.getCurrentRequestEvaluator();
        if (req_eval != null) {
            mode = req_eval.getLayer();
        } else {
            mode = DbKey.LIVE_LAYER;
        }
    }

    int maxResults = Integer.MAX_VALUE;
    try {
        maxResults = getMaxResults(options);
    } catch (Exception e) {
        maxResults = Integer.MAX_VALUE;
    }
    if (maxResults < 0) {
        maxResults = Integer.MAX_VALUE;
    }

    ArrayList protos = new ArrayList();
    if (prototypes != null && prototypes != Scriptable.NOT_FOUND) {
        QueryBean.setPrototypeArrays(this.app, prototypes, protos, new ArrayList(),
                new HashMap<String, ArrayList>());
    }

    IFilter theFilter = QueryBean.getFilterFromObject(filter);
    BooleanQuery primary = new BooleanQuery();
    ResourceProperties props = QueryBean.getResourceProperties(this.app, protos);
    parseFilterIntoQuery(theFilter, primary, props);

    int count = 0;
    for (int i = 0; i < size; i++) {
        Key[] node_keys = null;
        try {
            node_keys = (direction == 0
                    ? lmgr.getTargetNodeIds(objects.get(i).toString(), mode, protos, primary,
                            getLuceneSort(getSortObject(options)))
                    : lmgr.getSourceNodeIds(objects.get(i).toString(), mode, protos, primary,
                            getLuceneSort(getSortObject(options))));
        } catch (Exception ex) {
            ex.printStackTrace();
            node_keys = null;
            app.logError(ErrorReporter.errorMsg(this.getClass(), "getDirectionalNodesForCount")
                    + "Could not retrieve " + (direction == 0 ? "target" : "source") + " nodes", ex);
        }

        if (node_keys == null) {
            continue;
        }

        count += node_keys.length;

        if (count >= maxResults) {
            count = maxResults;
            break;
        }
    }

    return count;
}

From source file:axiom.scripting.rhino.QueryBean.java

License:Open Source License

public static ResourceProperties getResourceProperties(Application app, ArrayList prototypes) {
    int length = 0;
    final TypeManager tmgr = app.typemgr;
    ResourceProperties combined_props = new ResourceProperties();
    if (prototypes != null && (length = prototypes.size()) > 0) {
        BooleanQuery proto_query = new BooleanQuery();
        for (int i = 0; i < length; i++) {
            String prototype = (String) prototypes.get(i);

            Prototype proto = tmgr.getPrototype(prototype);
            Stack protos = new Stack();
            while (proto != null) {
                protos.push(proto);/*from www.j  av a 2 s .  c  o m*/
                proto = proto.getParentPrototype();
            }
            final int protoChainSize = protos.size();
            for (int j = 0; j < protoChainSize; j++) {
                proto = (Prototype) protos.pop();
                combined_props.putAll(proto.getTypeProperties());
            }
        }
    } else {
        ArrayList protoarr = app.getSearchablePrototypes();
        BooleanQuery proto_query = new BooleanQuery();
        for (int i = protoarr.size() - 1; i > -1; i--) {
            String protoName = (String) protoarr.get(i);

            Prototype proto = tmgr.getPrototype(protoName);
            Stack protos = new Stack();
            while (proto != null) {
                protos.push(proto);
                proto = proto.getParentPrototype();
            }
            final int protoChainSize = protos.size();
            for (int j = 0; j < protoChainSize; j++) {
                proto = (Prototype) protos.pop();
                combined_props.putAll(proto.getTypeProperties());
            }
        }
    }

    return combined_props;
}

From source file:be.ugent.tiwi.sleroux.newsrec.newsreclib.recommend.recommenders.LuceneTermRecommender.java

License:Apache License

protected Query buildQuery(Map<String, Double> terms) {
    BooleanQuery q = new BooleanQuery();
    for (String term : terms.keySet()) {
        Query query = new TermQuery(new Term("text", term));
        query.setBoost(terms.get(term).floatValue());
        q.add(query, BooleanClause.Occur.SHOULD);
        Query query2 = new TermQuery(new Term("title", term));
        query2.setBoost(terms.get(term).floatValue());
        q.add(query2, BooleanClause.Occur.SHOULD);
    }/*from  w  w w.  j a  v  a 2  s .  co m*/
    //return q;
    return new RecencyBoostQuery(q);
}

From source file:be.ugent.tiwi.sleroux.newsrec.newsreclib.recommend.recommenders.PersonalAndTrendingRecommender.java

License:Apache License

protected Query buildQuery(Map<String, Double> terms) {
    BooleanQuery q = new BooleanQuery();
    for (String term : terms.keySet()) {
        Query query = new TermQuery(new Term("description", term));
        query.setBoost(terms.get(term).floatValue());
        q.add(query, BooleanClause.Occur.SHOULD);
        Query query2 = new TermQuery(new Term("title", term));
        query2.setBoost(terms.get(term).floatValue() * 2);
        q.add(query2, BooleanClause.Occur.SHOULD);
    }// w  w  w.  j  a  va 2s  . c  o m
    //return q;
    return new RecencyBoostQuery(q);
}

From source file:be.ugent.tiwi.sleroux.newsrec.newsreclib.recommend.recommenders.TopNRecommender.java

License:Apache License

protected Query buildQuery(List<Long> ids) {
    BooleanQuery q = new BooleanQuery();
    float boost = 1.0F;
    float d = 0.5F / ids.size();
    for (long id : ids) {
        Query query = NumericRangeQuery.newLongRange("id", 1, id, id, true, true);
        query.setBoost(boost);/*from  w  w w .  j  a  v a  2s  .  co m*/
        boost -= d;
        q.add(query, BooleanClause.Occur.SHOULD);
    }

    return new RecencyBoostQuery(q, decay);
}

From source file:be.ugent.tiwi.sleroux.newsrec.newsreclib.recommend.recommenders.TrendingTopicRecommender.java

License:Apache License

protected Query buildQuery(String[] trends) {
    BooleanQuery q = new BooleanQuery();
    for (String term : trends) {
        Query query2 = new TermQuery(new Term("title", term));
        q.add(query2, BooleanClause.Occur.SHOULD);
    }/*from  ww w  . j  a  v  a2s .  c om*/

    RecencyBoostQuery rq = new RecencyBoostQuery(q, decay);

    return rq;
}

From source file:br.ufba.dcc.mestrado.computacao.repository.impl.ProjectRepositoryImpl.java

/**
 *
 * Encontra projetos que possuam as mesmas tags que o projeto  em questo
 * @param project Projeto para o qual se deseja encontrar projetos semelhantes
 * @returns Um objeto FullTextQuery contendo a lgica necessria para se encontrar projetos semelhantes
 *///from  w  ww.  ja va  2s.com
@Override
public FullTextQuery findRelatedProjects(OpenHubProjectEntity project) throws IOException {

    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(getEntityManager());
    BooleanQuery booleanQuery = new BooleanQuery();

    booleanQuery.add(new TermQuery(new Term(SearchFieldsEnum.projectName.fieldName(), project.getName())),
            BooleanClause.Occur.MUST_NOT);

    booleanQuery.add(new TermQuery(new Term("id", project.getId().toString())), BooleanClause.Occur.MUST_NOT);

    if (project.getTags() != null) {
        for (OpenHubTagEntity tag : project.getTags()) {
            TermQuery termQuery = new TermQuery(new Term(SearchFieldsEnum.tagName.fieldName(), tag.getName()));
            booleanQuery.add(termQuery, BooleanClause.Occur.SHOULD);
        }
    }

    booleanQuery.setMinimumNumberShouldMatch(3);

    FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(booleanQuery, getEntityClass());

    //configureRelevanceSort(fullTextQuery);

    return fullTextQuery;
}

From source file:br.ufmt.harmonizacao.implementer.PatenteeSearcher.java

public List<String> search(String field, String value) {
    try {//from  w  w  w .  ja v a 2s .co  m
        long start = System.currentTimeMillis();
        TokenStream stream = analyzer.tokenStream(field, new StringReader(value));
        CharTermAttribute attr = stream.getAttribute(CharTermAttribute.class);
        stream.reset();
        String valor = "";
        while (stream.incrementToken()) {
            valor = valor + attr.toString() + ' ';
        }
        BooleanQuery bq = new BooleanQuery();
        BooleanQuery acronymBq = null;
        String query = "";
        BooleanQuery wrapBq = new BooleanQuery();
        String[] tokens = valor.split(" ");
        for (int i = 0; i < tokens.length; i++) {
            if (tokens.length >= 2) {
                acronymBq = new BooleanQuery();
                switch (i) {
                case 0:
                    acronymBq.add(new PrefixQuery(new Term(field, tokens[i])), BooleanClause.Occur.MUST);
                    bq.add(new PrefixQuery(new Term(field, tokens[i])), BooleanClause.Occur.SHOULD);
                    break;
                case 1:
                    acronymBq.add(new FuzzyQuery(new Term(field, tokens[i])), BooleanClause.Occur.MUST_NOT);
                    bq.add(new FuzzyQuery(new Term(field, tokens[i])), BooleanClause.Occur.SHOULD);
                    bq.add(new LengthQuery(field, valor), BooleanClause.Occur.MUST_NOT);
                    break;
                default:
                    break;
                }
            } else {
                if (tokens[i].length() > 3) {
                    bq.add(new FuzzyQuery(new Term(field, tokens[i])), BooleanClause.Occur.MUST);
                } else {
                    bq.add(new TermQuery(new Term(field, tokens[i])), BooleanClause.Occur.MUST);
                }
            }
        }

        stream.end();
        stream.close();
        // Aqui termina
        // Cria uma fuzzyquery, ela que far a busca de aproximao

        wrapBq.add(bq, BooleanClause.Occur.MUST);
        if (acronymBq != null) {
            //new QueryParser(Version.LUCENE_47, field, new StandardAnalyzer(Version.LUCENE_47)).parse(query)
            wrapBq.add(acronymBq, BooleanClause.Occur.MUST_NOT);
        }
        String queryTime = "Tempo para construo da query : " + (System.currentTimeMillis() - start) + "ms";
        // Pegando os documentos encontrado na pesquisa
        start = System.currentTimeMillis();
        ScoreDoc[] hits = searcher.search(wrapBq, 10).scoreDocs;
        String searchTime = "Tempo para busca : " + (System.currentTimeMillis() - start) + "ms";
        List<String> result = new ArrayList<String>();
        result.add(valor);
        if (hits.length > 0) {
            for (int i = 0; i < hits.length; i++) {
                Document hitDoc = searcher.doc(hits[i].doc);
                result.add(hitDoc.get(field));
            }
        }
        result.add(queryTime);
        result.add(searchTime);
        return result;
    } catch (IOException ex) {
        Logger.getLogger(PatenteeSearcher.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}