/**
  * 将分支数据转成Query逻辑
  *
  * @return
  */
 List<Query> toQueries(String fieldName) {
   List<Query> queries = new ArrayList<Query>(1);
   // 生成当前branch 的query
   if (lexeme != null) {
     queries.add(new TermQuery(new Term(fieldName, lexeme.getLexemeText())));
   }
   // 生成child branch 的query
   if (acceptedBranchs != null && acceptedBranchs.size() > 0) {
     if (acceptedBranchs.size() == 1) {
       Query onlyOneQuery = optimizeQueries(acceptedBranchs.get(0).toQueries(fieldName));
       if (onlyOneQuery != null) {
         queries.add(onlyOneQuery);
       }
     } else {
       BooleanQuery orQuery = new BooleanQuery();
       for (TokenBranch childBranch : acceptedBranchs) {
         Query childQuery = optimizeQueries(childBranch.toQueries(fieldName));
         if (childQuery != null) {
           orQuery.add(childQuery, Occur.SHOULD);
         }
       }
       if (orQuery.getClauses().length > 0) {
         queries.add(orQuery);
       }
     }
   }
   // 生成nextBranch的query
   if (nextBranch != null) {
     queries.addAll(nextBranch.toQueries(fieldName));
   }
   return queries;
 }
 @Override
 public Query prefixQuery(
     Object value,
     @Nullable MultiTermQuery.RewriteMethod method,
     @Nullable QueryParseContext context) {
   if (fieldType.indexOptions() != IndexOptions.NONE || context == null) {
     return super.prefixQuery(value, method, context);
   }
   Collection<String> queryTypes = context.queryTypes();
   if (queryTypes.size() == 1) {
     PrefixQuery prefixQuery =
         new PrefixQuery(
             new Term(
                 UidFieldMapper.NAME,
                 Uid.createUidAsBytes(
                     Iterables.getFirst(queryTypes, null), BytesRefs.toBytesRef(value))));
     if (method != null) {
       prefixQuery.setRewriteMethod(method);
     }
     return prefixQuery;
   }
   BooleanQuery query = new BooleanQuery();
   for (String queryType : queryTypes) {
     PrefixQuery prefixQuery =
         new PrefixQuery(
             new Term(
                 UidFieldMapper.NAME,
                 Uid.createUidAsBytes(queryType, BytesRefs.toBytesRef(value))));
     if (method != null) {
       prefixQuery.setRewriteMethod(method);
     }
     query.add(prefixQuery, BooleanClause.Occur.SHOULD);
   }
   return query;
 }
Exemple #3
0
 /** 获取全文查询对象 */
 public BooleanQuery getFullTextQuery(BooleanClause... booleanClauses) {
   BooleanQuery booleanQuery = new BooleanQuery();
   for (BooleanClause booleanClause : booleanClauses) {
     booleanQuery.add(booleanClause);
   }
   return booleanQuery;
 }
  @Test
  public void testQueryText() {

    Float boost = 0.7f;
    Object[] values = new Object[] {"houses", "cats"};

    Schema schema = schema().mapper("name", textMapper()).defaultAnalyzer("english").build();

    ContainsCondition condition = new ContainsCondition(boost, "name", values);
    Query query = condition.query(schema);
    assertNotNull("Query is not built", query);
    assertEquals("Query type is wrong", BooleanQuery.class, query.getClass());

    BooleanQuery booleanQuery = (BooleanQuery) query;
    assertEquals("Query boost is wrong", 0.7f, query.getBoost(), 0);
    BooleanClause[] clauses = booleanQuery.getClauses();
    assertEquals(
        "Query is wrong",
        "hous",
        ((TermQuery) clauses[0].getQuery()).getTerm().bytes().utf8ToString());
    assertEquals(
        "Query is wrong",
        "cat",
        ((TermQuery) clauses[1].getQuery()).getTerm().bytes().utf8ToString());
  }
  public List<Document> searchDocuments(String text) {
    List<Document> documents = new ArrayList<Document>();
    try {
      TokenStream tokenStream = analyzer.tokenStream("text", text);
      CharTermAttribute charTermAtt = tokenStream.addAttribute(CharTermAttribute.class);
      tokenStream.reset();
      BooleanQuery bQuery = new BooleanQuery();
      while (tokenStream.incrementToken()) {
        String token = charTermAtt.toString();
        TermQuery tq = new TermQuery(new Term("text", token));
        tq.setBoost(2f);

        bQuery.add(tq, Occur.MUST);
      }
      tokenStream.close();

      TopDocs results = searcher.search(bQuery, 100000);
      ScoreDoc[] hits = results.scoreDocs;
      for (ScoreDoc hit : hits) {
        Document doc = searcher.doc(hit.doc);
        doc.add(new FloatField("score", hit.score, FloatField.TYPE_STORED));
        documents.add(doc);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return documents;
  }
  public void performWork(LuceneWork work, IndexWriter writer) {
    final Class<?> entityType = work.getEntityClass();
    final Serializable id = work.getId();
    log.tracef("Removing %s#%s by query.", entityType, id);
    DocumentBuilderIndexedEntity<?> builder = workspace.getDocumentBuilder(entityType);

    BooleanQuery entityDeletionQuery = new BooleanQuery();

    Query idQueryTerm;
    if (isIdNumeric(builder)) {
      idQueryTerm = NumericFieldUtils.createExactMatchQuery(builder.getIdKeywordName(), id);
    } else {
      idQueryTerm = new TermQuery(builder.getTerm(id));
    }
    entityDeletionQuery.add(idQueryTerm, BooleanClause.Occur.MUST);

    Term classNameQueryTerm = new Term(ProjectionConstants.OBJECT_CLASS, entityType.getName());
    TermQuery classNameQuery = new TermQuery(classNameQueryTerm);
    entityDeletionQuery.add(classNameQuery, BooleanClause.Occur.MUST);

    try {
      writer.deleteDocuments(entityDeletionQuery);
    } catch (Exception e) {
      String message = "Unable to remove " + entityType + "#" + id + " from index.";
      throw new SearchException(message, e);
    }
  }
  public Query parse() throws ParseException {
    String pattern = qstr;
    int idx = qstr.indexOf("title:");
    if (idx < 0) return keyParser.parse(qstr);
    pattern = qstr.substring(0, idx);
    String title = qstr.substring(idx + 6);

    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < title.length(); i++) {
      char c = title.charAt(i);
      for (int k = 0; k < TpWorkingData.SPECIALS.length; k++) {
        if (c != TpWorkingData.SPECIALS[k]) continue;
        builder.append('\\');
        break;
      }
      builder.append(c);
    }
    title = builder.toString();

    BooleanQuery patternQuery = new BooleanQuery();
    patternQuery.add(keyParser.parse(pattern), BooleanClause.Occur.SHOULD);
    if (title.trim().length() > 0) {
      patternQuery.add(titleParser.parse(title), BooleanClause.Occur.SHOULD);
    }
    //    return keyParser.parse(qstr);
    //    System.out.println(" thay co "+ patternQuery);

    return patternQuery;
  }
Exemple #8
0
  public CObj getMyIdentity(String id) {
    BooleanQuery bq = new BooleanQuery();
    Term typterm = new Term(CObj.PARAM_TYPE, CObj.IDENTITY);
    bq.add(new TermQuery(typterm), BooleanClause.Occur.MUST);

    Term idterm = new Term(CObj.PARAM_ID, id);
    bq.add(new TermQuery(idterm), BooleanClause.Occur.MUST);

    Term mustterm = new Term(CObj.docPrivate(CObj.MINE), "true");
    bq.add(new TermQuery(mustterm), BooleanClause.Occur.MUST);

    CObj r = null;
    CObjList l = search(bq, 1);

    if (l.size() > 0) {
      try {
        r = l.get(0);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    l.close();
    return r;
  }
  public void testStraightFilters() {
    createData();
    FullTextSession s = Search.getFullTextSession(openSession());
    s.getTransaction().begin();
    BooleanQuery query = new BooleanQuery();
    query.add(new TermQuery(new Term("teacher", "andre")), BooleanClause.Occur.SHOULD);
    query.add(new TermQuery(new Term("teacher", "max")), BooleanClause.Occur.SHOULD);
    query.add(new TermQuery(new Term("teacher", "aaron")), BooleanClause.Occur.SHOULD);
    FullTextQuery ftQuery;

    ftQuery = s.createFullTextQuery(query, Driver.class);
    ftQuery.enableFullTextFilter("bestDriver");
    Filter dateFilter = new TermRangeFilter("delivery", "2001", "2005", true, true);
    ftQuery.setFilter(dateFilter);
    assertEquals("Should select only liz", 1, ftQuery.getResultSize());

    ftQuery = s.createFullTextQuery(query, Driver.class);
    ftQuery.setFilter(dateFilter);
    ftQuery.enableFullTextFilter("bestDriver");
    ftQuery.enableFullTextFilter("security").setParameter("login", "andre");
    ftQuery.disableFullTextFilter("security");
    ftQuery.disableFullTextFilter("bestDriver");
    ftQuery.setFilter(null);
    assertEquals("Should not filter anymore", 3, ftQuery.getResultSize());

    s.getTransaction().commit();
    s.close();
    deleteData();
  }
Exemple #10
0
  public CObjList searchFiles(String comid, String share, String qstr, Sort srt) {
    BooleanQuery query = new BooleanQuery();

    Term pstterm = new Term(CObj.PARAM_TYPE, CObj.FILE);
    query.add(new TermQuery(pstterm), BooleanClause.Occur.MUST);

    Term comterm = new Term(CObj.docString(CObj.COMMUNITYID), comid);
    query.add(new TermQuery(comterm), BooleanClause.Occur.MUST);

    NumericRangeQuery<Long> nq =
        NumericRangeQuery.newLongRange(
            CObj.docNumber(CObj.NUMBER_HAS), 0L, Long.MAX_VALUE, false, true);
    query.add(nq, BooleanClause.Occur.MUST);

    if (share != null) {
      Term shareterm = new Term(CObj.docString(CObj.SHARE_NAME), share);
      query.add(new TermQuery(shareterm), BooleanClause.Occur.MUST);
    }

    Matcher m = Pattern.compile("\\S+").matcher(qstr);

    if (m.find()) {
      StringBuilder sb = new StringBuilder();
      sb.append(CObj.docStringText(CObj.NAME));
      sb.append(":\"");
      sb.append(qstr);
      sb.append("\"");
      return search(query, sb.toString(), Integer.MAX_VALUE, srt);
    } else {
      return search(query, Integer.MAX_VALUE, srt);
    }
  }
Exemple #11
0
  public CObjList getAllHasFiles() {
    BooleanQuery bq = new BooleanQuery();
    Term typterm = new Term(CObj.PARAM_TYPE, CObj.HASFILE);
    bq.add(new TermQuery(typterm), BooleanClause.Occur.MUST);

    return search(bq, Integer.MAX_VALUE);
  }
Exemple #12
0
  public CObjList searchPosts(String comid, String qstr, Sort srt) {
    BooleanQuery query = new BooleanQuery();

    Term pstterm = new Term(CObj.PARAM_TYPE, CObj.POST);
    query.add(new TermQuery(pstterm), BooleanClause.Occur.MUST);

    Term comterm = new Term(CObj.docString(CObj.COMMUNITYID), comid);
    query.add(new TermQuery(comterm), BooleanClause.Occur.MUST);

    Matcher m = Pattern.compile("\\S+").matcher(qstr);

    if (m.find()) {
      StringBuilder sb = new StringBuilder();
      sb.append(CObj.docStringText(CObj.SUBJECT));
      sb.append(":\"");
      sb.append(qstr);
      sb.append("\" OR ");
      sb.append(CObj.docText(CObj.BODY));
      sb.append(":\"");
      sb.append(qstr);
      sb.append("\" OR ");
      sb.append(CObj.docStringText(CObj.NAME));
      sb.append(":\"");
      sb.append(qstr);
      sb.append("\"");
      return search(query, sb.toString(), Integer.MAX_VALUE, srt);
    } else {
      return search(query, Integer.MAX_VALUE, srt);
    }
  }
Exemple #13
0
  public CObjList getIdentities() {
    BooleanQuery bq = new BooleanQuery();
    Term typterm = new Term(CObj.PARAM_TYPE, CObj.IDENTITY);
    bq.add(new TermQuery(typterm), BooleanClause.Occur.MUST);

    return search(bq, Integer.MAX_VALUE);
  }
Exemple #14
0
  public CObj getSubscriptionUnsub(String comid, String memid) {
    BooleanQuery bq = new BooleanQuery();
    Term typterm = new Term(CObj.PARAM_TYPE, CObj.SUBSCRIPTION);
    bq.add(new TermQuery(typterm), BooleanClause.Occur.MUST);

    Term cidterm = new Term(CObj.docString(CObj.COMMUNITYID), comid);
    bq.add(new TermQuery(cidterm), BooleanClause.Occur.MUST);

    Term midterm = new Term(CObj.docString(CObj.CREATOR), memid);
    bq.add(new TermQuery(midterm), BooleanClause.Occur.MUST);

    CObj r = null;
    CObjList l = search(bq, 1);

    if (l.size() > 0) {
      try {
        r = l.get(0);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    l.close();
    return r;
  }
  public SearchResponse search(SearchRequest request) {
    SolrQuery query = new SolrQuery();
    query.setRows(request.getLimit());
    query.setStart(request.getOffset() * request.getLimit());
    BooleanQuery aggregate = new BooleanQuery();
    if (!StringUtils.isBlank(request.getText())) {
      TermQuery termQuery = new TermQuery(new Term("", request.getText()));
      aggregate.add(termQuery, BooleanClause.Occur.SHOULD);
    }
    if (!StringUtils.isBlank(request.getEventId())) {
      aggregate.add(
          new TermQuery(new Term("eventid", request.getEventId())), BooleanClause.Occur.MUST);
    }
    query.setQuery(aggregate.toString());

    log.info("QUERY IS: " + query.toString());
    try {
      QueryResponse queryResponse = solrServer.query(query);
      log.info("RESPONSE FROM QUERY WAS: " + queryResponse);
      SolrDocumentList results = queryResponse.getResults();
      log.info("RESULTS WAS: " + results);
      ArrayList<SearchResponse.Hit> hits = new ArrayList<SearchResponse.Hit>();
      for (SolrDocument result : results) {
        hits.add(
            new SearchResponse.Hit(
                ObjectType.session, String.valueOf(result.getFieldValue("id")), null));
      }
      return new SearchResponse(results.getNumFound(), queryResponse.getElapsedTime(), hits);
    } catch (SolrServerException e) {
      e.printStackTrace();
    }
    return null;
  }
  public void testNamedFilters() {
    createData();
    FullTextSession s = Search.getFullTextSession(openSession());
    s.getTransaction().begin();
    BooleanQuery query = new BooleanQuery();
    query.add(new TermQuery(new Term("teacher", "andre")), BooleanClause.Occur.SHOULD);
    query.add(new TermQuery(new Term("teacher", "max")), BooleanClause.Occur.SHOULD);
    query.add(new TermQuery(new Term("teacher", "aaron")), BooleanClause.Occur.SHOULD);
    FullTextQuery ftQuery = s.createFullTextQuery(query, Driver.class);
    assertEquals("No filter should happen", 3, ftQuery.getResultSize());

    ftQuery = s.createFullTextQuery(query, Driver.class);
    ftQuery.disableFullTextFilter("bestDriver"); // was not enabled, but should be harmless
    ftQuery.enableFullTextFilter("bestDriver");
    assertEquals("Should filter out Gavin", 2, ftQuery.getResultSize());

    ftQuery = s.createFullTextQuery(query, Driver.class);
    ftQuery.enableFullTextFilter("bestDriver");
    ftQuery.enableFullTextFilter("security").setParameter("login", "andre");
    assertEquals("Should filter to limit to Emmanuel", 1, ftQuery.getResultSize());

    ftQuery = s.createFullTextQuery(query, Driver.class);
    ftQuery.enableFullTextFilter("bestDriver");
    ftQuery.enableFullTextFilter("security").setParameter("login", "andre");
    ftQuery.disableFullTextFilter("security");
    ftQuery.disableFullTextFilter("bestDriver");
    assertEquals("Should not filter anymore", 3, ftQuery.getResultSize());

    s.getTransaction().commit();
    s.close();
    deleteData();
  }
  // LUCENE-5725
  public void testMultiValues() throws Exception {
    MoreLikeThis mlt = new MoreLikeThis(reader);
    Analyzer analyzer = new MockAnalyzer(random(), MockTokenizer.KEYWORD, false);
    mlt.setAnalyzer(analyzer);
    mlt.setMinDocFreq(1);
    mlt.setMinTermFreq(1);
    mlt.setMinWordLen(1);
    mlt.setFieldNames(new String[] {"text"});

    BooleanQuery query =
        (BooleanQuery)
            mlt.like(
                "text",
                new StringReader("lucene"),
                new StringReader("lucene release"),
                new StringReader("apache"),
                new StringReader("apache lucene"));
    Collection<BooleanClause> clauses = query.clauses();
    assertEquals("Expected 2 clauses only!", 2, clauses.size());
    for (BooleanClause clause : clauses) {
      Term term = ((TermQuery) clause.getQuery()).getTerm();
      assertTrue(
          Arrays.asList(new Term("text", "lucene"), new Term("text", "apache")).contains(term));
    }
    analyzer.close();
  }
 public static Query createMultiIntQuery(String field, int[] ids) {
   BooleanQuery query = new BooleanQuery();
   for (int id : ids) {
     query.add(NumericRangeQuery.newIntRange(field, id, id, true, true), Occur.SHOULD);
   }
   return query;
 }
  /**
   * Adds one dimension of drill downs; if you pass multiple values they are OR'd, and then the
   * entire dimension is AND'd against the base query.
   */
  public void add(CategoryPath... paths) {
    Query q;
    if (paths[0].length == 0) {
      throw new IllegalArgumentException("all CategoryPaths must have length > 0");
    }
    String dim = paths[0].components[0];
    if (drillDownDims.containsKey(dim)) {
      throw new IllegalArgumentException("dimension '" + dim + "' was already added");
    }
    if (paths.length == 1) {
      q = new TermQuery(term(fip, paths[0]));
    } else {
      BooleanQuery bq = new BooleanQuery(true); // disable coord
      for (CategoryPath cp : paths) {
        if (cp.length == 0) {
          throw new IllegalArgumentException("all CategoryPaths must have length > 0");
        }
        if (!cp.components[0].equals(dim)) {
          throw new IllegalArgumentException(
              "multiple (OR'd) drill-down paths must be under same dimension; got '"
                  + dim
                  + "' and '"
                  + cp.components[0]
                  + "'");
        }
        bq.add(new TermQuery(term(fip, cp)), Occur.SHOULD);
      }
      q = bq;
    }

    add(dim, q);
  }
 public static Query createMultiTermQuery(String field, String[] terms) {
   BooleanQuery query = new BooleanQuery();
   for (String term : terms) {
     query.add(new TermQuery(new Term(field, term)), Occur.SHOULD);
   }
   return query;
 }
  @Override
  public BooleanQuery build(QueryNode queryNode) throws QueryNodeException {
    AnyQueryNode andNode = (AnyQueryNode) queryNode;

    BooleanQuery bQuery = new BooleanQuery();
    List<QueryNode> children = andNode.getChildren();

    if (children != null) {

      for (QueryNode child : children) {
        Object obj = child.getTag(QueryTreeBuilder.QUERY_TREE_BUILDER_TAGID);

        if (obj != null) {
          Query query = (Query) obj;

          try {
            bQuery.add(query, BooleanClause.Occur.SHOULD);
          } catch (TooManyClauses ex) {

            throw new QueryNodeException(
                new MessageImpl(/*
             * IQQQ.Q0028E_TOO_MANY_BOOLEAN_CLAUSES,
             * BooleanQuery.getMaxClauseCount()
             */ QueryParserMessages.EMPTY_MESSAGE), ex);
          }
        }
      }
    }

    bQuery.setMinimumNumberShouldMatch(andNode.getMinimumMatchingElements());

    return bQuery;
  }
  /**
   * Makes a flag based query clause. This is where searches can filtered by portal.
   *
   * <p>If you think that search is not working correctly with protals and all that kruft then this
   * is a method you want to look at.
   *
   * <p>It only takes into account "the portal flag" and flag1Exclusive must be set. Where does that
   * stuff get set? Look in vitro.flags.PortalFlag
   *
   * <p>One thing to keep in mind with portal filtering and search is that if you want to search a
   * portal that is different then the portal the user is 'in' then the home parameter should be set
   * to force the user into the new portal.
   *
   * <p>Ex. Bob requests the search page for vivo in portal 3. You want to have a drop down menu so
   * bob can search the all CALS protal, id 60. You need to have a home=60 on your search form. If
   * you don't set home=60 with your search query, then the search will not be in the all portal AND
   * the WebappDaoFactory will be filtered to only show things in portal 3.
   *
   * <p>Notice: flag1 as a parameter is ignored. bdc34 2009-05-22.
   */
  @SuppressWarnings("static-access")
  private Query makeFlagQuery(PortalFlag flag) {
    if (flag == null
        || !flag.isFilteringActive()
        || flag.getFlag1DisplayStatus() == flag.SHOW_ALL_PORTALS) return null;

    // make one term for each bit in the numeric flag that is set
    Collection<TermQuery> terms = new LinkedList<TermQuery>();
    int portalNumericId = flag.getFlag1Numeric();
    Long[] bits = FlagMathUtils.numeric2numerics(portalNumericId);
    for (Long bit : bits) {
      terms.add(new TermQuery(new Term(Entity2LuceneDoc.term.PORTAL, Long.toString(bit))));
    }

    // make a boolean OR query for all of those terms
    BooleanQuery boolQuery = new BooleanQuery();
    if (terms.size() > 0) {
      for (TermQuery term : terms) {
        boolQuery.add(term, BooleanClause.Occur.SHOULD);
      }
      return boolQuery;
    } else {
      // we have no flags set, so no flag filtering
      return null;
    }
  }
  public Map<String, Double> search(String text) {
    Map<String, Double> similar = new HashMap<String, Double>();
    try {
      TokenStream tokenStream = analyzer.tokenStream("text", text);
      CharTermAttribute charTermAtt = tokenStream.addAttribute(CharTermAttribute.class);
      tokenStream.reset();
      BooleanQuery bQuery = new BooleanQuery();
      while (tokenStream.incrementToken()) {
        String token = charTermAtt.toString();
        TermQuery tq = new TermQuery(new Term("text", token));
        tq.setBoost(2f);

        bQuery.add(tq, Occur.MUST);
      }
      tokenStream.close();

      TopDocs results = searcher.search(bQuery, 100000);
      ScoreDoc[] hits = results.scoreDocs;
      for (ScoreDoc hit : hits) {
        Document doc = searcher.doc(hit.doc);
        similar.put(doc.get("id"), new Double(hit.score));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return similar;
  }
  /**
   * @return
   * @throws Exception
   */
  public Query getQuery() throws Exception {
    PaodingAnalyzer analyzer = new PaodingAnalyzer();
    String field = "contents";
    Query query = null;

    BooleanQuery booleanQuery = new BooleanQuery();

    if (this.qtype.equals("term")) {
      QueryParser parser = new QueryParser(Version.LUCENE_44, field, analyzer);
      query = parser.parse(queryStr);

    } else if ("fuzz".equals(this.qtype)) {
      Term term = new Term(field, queryStr);
      query = new FuzzyQuery(term);
    } else {
      Term term = new Term(field, queryStr);
      query = new PrefixQuery(term);
    }
    if (!"all".equals(this.docType)) {
      Term typeTerm = new Term("type", this.docType);
      TermQuery typeQuery = new TermQuery(typeTerm);
      booleanQuery.add(typeQuery, BooleanClause.Occur.MUST);
    }

    // System.out.println("--this.docType---"+this.docType);
    booleanQuery.add(query, BooleanClause.Occur.MUST);

    return booleanQuery;
  }
 public void testNormalization() throws IOException {
   assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0);
   GeoBoundingBoxQueryBuilder qb = createTestQueryBuilder();
   if (getCurrentTypes().length != 0 && "mapped_geo".equals(qb.fieldName())) {
     // only execute this test if we are running on a valid geo field
     qb.setCorners(200, 200, qb.bottomRight().getLat(), qb.bottomRight().getLon());
     qb.setValidationMethod(GeoValidationMethod.COERCE);
     Query query = qb.toQuery(createShardContext());
     if (query instanceof ConstantScoreQuery) {
       ConstantScoreQuery result = (ConstantScoreQuery) query;
       BooleanQuery bboxFilter = (BooleanQuery) result.getQuery();
       for (BooleanClause clause : bboxFilter.clauses()) {
         LegacyNumericRangeQuery boundary = (LegacyNumericRangeQuery) clause.getQuery();
         if (boundary.getMax() != null) {
           assertTrue(
               "If defined, non of the maximum range values should be larger than 180",
               boundary.getMax().intValue() <= 180);
         }
       }
     } else {
       assertTrue(
           "memory queries should result in LegacyInMemoryGeoBoundingBoxQuery",
           query instanceof LegacyInMemoryGeoBoundingBoxQuery);
     }
   }
 }
 public Query createCommonTermsQuery(
     String field,
     String queryText,
     Occur highFreqOccur,
     Occur lowFreqOccur,
     float maxTermFrequency,
     MappedFieldType fieldType) {
   Query booleanQuery = createBooleanQuery(field, queryText, lowFreqOccur);
   if (booleanQuery != null && booleanQuery instanceof BooleanQuery) {
     BooleanQuery bq = (BooleanQuery) booleanQuery;
     ExtendedCommonTermsQuery query =
         new ExtendedCommonTermsQuery(
             highFreqOccur,
             lowFreqOccur,
             maxTermFrequency,
             ((BooleanQuery) booleanQuery).isCoordDisabled(),
             fieldType);
     for (BooleanClause clause : bq.clauses()) {
       if (!(clause.getQuery() instanceof TermQuery)) {
         return booleanQuery;
       }
       query.add(((TermQuery) clause.getQuery()).getTerm());
     }
     return query;
   }
   return booleanQuery;
 }
  public DiscoveryResponse discoverLatestVersion(DiscoveryRequest req)
      throws NoSuchRepositoryException, IOException {
    CLvoKey info = req.getLvoKey();

    IndexingContext localContext =
        indexerManager.getRepositoryLocalIndexContext(info.getRepositoryId());
    IndexingContext remoteContext =
        indexerManager.getRepositoryRemoteIndexContext(info.getRepositoryId());

    BooleanQuery bq = new BooleanQuery();
    bq.add(indexerManager.constructQuery(ArtifactInfo.GROUP_ID, info.getGroupId()), Occur.MUST);
    bq.add(
        indexerManager.constructQuery(ArtifactInfo.ARTIFACT_ID, info.getArtifactId()), Occur.MUST);

    // to have sorted results by version in descending order
    FlatSearchRequest sreq = new FlatSearchRequest(bq, ArtifactInfo.REPOSITORY_VERSION_COMPARATOR);

    sreq.getContexts().add(localContext);

    sreq.getContexts().add(remoteContext);

    FlatSearchResponse hits = indexerManager.getNexusIndexer().searchFlat(sreq);

    DiscoveryResponse response = new DiscoveryResponse(req);

    if (hits.getTotalHits() > 0) {
      // found it, they are sorted in descending order, so the 1st one is the newest
      response.setVersion(hits.getResults().iterator().next().version);

      response.setSuccessful(true);
    }

    return response;
  }
  public void testDefaultMinShouldMatch() throws Exception {
    // Queries have a minShouldMatch of 0
    BooleanQuery bq =
        (BooleanQuery)
            parseQuery(boolQuery().must(termQuery("foo", "bar")).buildAsBytes())
                .toQuery(createShardContext());
    assertEquals(0, bq.getMinimumNumberShouldMatch());

    bq =
        (BooleanQuery)
            parseQuery(boolQuery().should(termQuery("foo", "bar")).buildAsBytes())
                .toQuery(createShardContext());
    assertEquals(0, bq.getMinimumNumberShouldMatch());

    // Filters have a minShouldMatch of 0/1
    ConstantScoreQuery csq =
        (ConstantScoreQuery)
            parseQuery(constantScoreQuery(boolQuery().must(termQuery("foo", "bar"))).buildAsBytes())
                .toQuery(createShardContext());
    bq = (BooleanQuery) csq.getQuery();
    assertEquals(0, bq.getMinimumNumberShouldMatch());

    csq =
        (ConstantScoreQuery)
            parseQuery(
                    constantScoreQuery(boolQuery().should(termQuery("foo", "bar"))).buildAsBytes())
                .toQuery(createShardContext());
    bq = (BooleanQuery) csq.getQuery();
    assertEquals(1, bq.getMinimumNumberShouldMatch());
  }
  /**
   * Make sure the correct search is performed when theh search request does contain "update date"
   * critera and we have determined that they be included in the comment search.
   *
   * @throws Exception indicates some unexpected failure.
   */
  @Test
  public void testGetRecentCommentsIssuesUpdatedFromToDate() throws Exception {
    final String beforeDuration = "-3d";
    final Date beforeDate = dateSupport.convertToDate(beforeDuration);
    final Date afterDate = createDate(1981, Calendar.JANUARY, 12);
    final User user = new MockUser("me");

    final JqlQueryBuilder builder = JqlQueryBuilder.newBuilder();
    builder
        .where()
        .updated()
        .ltEq(beforeDuration)
        .and()
        .updatedAfter(afterDate)
        .and()
        .priority("major");
    final SearchRequest request = new SearchRequest(builder.buildQuery());

    final List<Long> issueIds = CollectionBuilder.newBuilder(6L, 3L, 13484L, 11111134L).asList();
    final BooleanQuery query = createIssueQuery(issueIds);

    final BooleanQuery dateQuery = new BooleanQuery();
    dateQuery.add(createBeforeQuery(beforeDate), BooleanClause.Occur.MUST);
    dateQuery.add(createAfterQuery(afterDate), BooleanClause.Occur.MUST);

    query.add(dateQuery, BooleanClause.Occur.MUST);

    _testGetRecentComments(issueIds, request, user, true, query);
  }
Exemple #30
0
  /**
   * 多Field,多条件,多Occur查询分析
   *
   * @param fields
   * @param queries
   * @param flags
   * @return Query 查询逻辑对象
   * @throws IOException
   */
  public static Query parseMultiField(
      String[] fields, String[] queries, BooleanClause.Occur[] flags) throws IOException {
    if (fields == null) {
      throw new IllegalArgumentException("parameter \"fields\" is null");
    }
    if (queries == null) {
      throw new IllegalArgumentException("parameter \"queries\" is null");
    }
    if (flags == null) {
      throw new IllegalArgumentException("parameter \"flags\" is null");
    }

    if (!(queries.length == fields.length && queries.length == flags.length)) {
      throw new IllegalArgumentException(
          "queries, fields, and flags array have have different length");
    }

    BooleanQuery resultQuery = new BooleanQuery();
    for (int i = 0; i < fields.length; i++) {
      if (fields[i] != null) {
        Query partQuery = parse(fields[i], queries[i]);
        if (partQuery != null
            && (!(partQuery instanceof BooleanQuery)
                || ((BooleanQuery) partQuery).getClauses().length > 0)) {
          resultQuery.add(partQuery, flags[i]);
        }
      }
    }
    return resultQuery;
  }