Java Code Examples for org.apache.lucene.search.BooleanQuery#add()

The following examples show how to use org.apache.lucene.search.BooleanQuery#add() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LuceneMessageSearchIndex.java    From james-project with Apache License 2.0 6 votes vote down vote up
private Flags retrieveFlags(Mailbox mailbox, MessageUid uid) throws IOException {
    try (IndexSearcher searcher = new IndexSearcher(IndexReader.open(writer, true))) {
        Flags retrievedFlags = new Flags();

        BooleanQuery query = new BooleanQuery();
        query.add(new TermQuery(new Term(MAILBOX_ID_FIELD, mailbox.getMailboxId().serialize())), BooleanClause.Occur.MUST);
        query.add(createQuery(MessageRange.one(uid)), BooleanClause.Occur.MUST);
        query.add(new PrefixQuery(new Term(FLAGS_FIELD, "")), BooleanClause.Occur.MUST);

        TopDocs docs = searcher.search(query, 100000);
        ScoreDoc[] sDocs = docs.scoreDocs;
        for (ScoreDoc sDoc : sDocs) {
            Document doc = searcher.doc(sDoc.doc);

            Stream.of(doc.getValues(FLAGS_FIELD))
                .forEach(flag -> fromString(flag).ifPresentOrElse(retrievedFlags::add, () -> retrievedFlags.add(flag)));
        }
        return retrievedFlags;
    }
}
 
Example 2
Source File: TripleIndexCreatorContext.java    From AGDISTIS with GNU Affero General Public License v3.0 6 votes vote down vote up
public List<Triple> search(String subject, String predicate, String object, int maxNumberOfResults) {
	BooleanQuery bq = new BooleanQuery();
	List<Triple> triples = new ArrayList<Triple>();
	try {
		if (subject != null && subject.equals("http://aksw.org/notInWiki")) {
			log.error(
					"A subject 'http://aksw.org/notInWiki' is searched in the index. That is strange and should not happen");
		}
		if (subject != null) {
			TermQuery tq = new TermQuery(new Term(FIELD_NAME_URI, subject));
			bq.add(tq, BooleanClause.Occur.MUST);
		}
		triples = getFromIndex(maxNumberOfResults, bq);
		if (triples == null) {
			return new ArrayList<Triple>();
		}

	} catch (Exception e) {
		log.error(e.getLocalizedMessage() + " -> " + subject);

	}
	return triples;
}
 
Example 3
Source File: LuceneMessageSearchIndex.java    From james-project with Apache License 2.0 6 votes vote down vote up
private void update(MailboxId mailboxId, MessageUid uid, Flags f) throws IOException {
    try (IndexSearcher searcher = new IndexSearcher(IndexReader.open(writer, true))) {
        BooleanQuery query = new BooleanQuery();
        query.add(new TermQuery(new Term(MAILBOX_ID_FIELD, mailboxId.serialize())), BooleanClause.Occur.MUST);
        query.add(createQuery(MessageRange.one(uid)), BooleanClause.Occur.MUST);
        query.add(new PrefixQuery(new Term(FLAGS_FIELD, "")), BooleanClause.Occur.MUST);

        TopDocs docs = searcher.search(query, 100000);
        ScoreDoc[] sDocs = docs.scoreDocs;
        for (ScoreDoc sDoc : sDocs) {
            Document doc = searcher.doc(sDoc.doc);

            doc.removeFields(FLAGS_FIELD);
            indexFlags(doc, f);

            writer.updateDocument(new Term(ID_FIELD, doc.get(ID_FIELD)), doc);
        }
    }
}
 
Example 4
Source File: BooleanQueryConstructor.java    From linden with Apache License 2.0 6 votes vote down vote up
@Override
protected Query construct(LindenQuery lindenQuery, LindenConfig config) throws Exception {
  if (lindenQuery.isSetBooleanQuery()) {
    LindenBooleanQuery ldBoolQuery = lindenQuery.getBooleanQuery();
    BooleanQuery booleanQuery = new BooleanQuery(ldBoolQuery.isDisableCoord());
    for (LindenBooleanSubQuery subQuery : ldBoolQuery.getQueries()) {
      Query query = constructQuery(subQuery.getQuery(), config);
      switch (subQuery.getClause()) {
        case SHOULD:
          booleanQuery.add(query, BooleanClause.Occur.SHOULD);
          break;
        case MUST:
          booleanQuery.add(query, BooleanClause.Occur.MUST);
          break;
        case MUST_NOT:
          booleanQuery.add(query, BooleanClause.Occur.MUST_NOT);
          break;
        default:
          throw new IOException("This should never happen, boolean clause is " + subQuery.getClause());
      }
    }
    return booleanQuery;
  }
  return null;
}
 
Example 5
Source File: ZipscriptQueryExtension.java    From drftpd with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void addQueryTerms(BooleanQuery query, AdvancedSearchParams params) {
    try {
        ZipscriptQueryParams queryParams = params.getExtensionData(ZipscriptQueryParams.ZIPSCRIPTQUERYPARAMS);
        if (queryParams.getMinPresent() != null || queryParams.getMaxPresent() != null) {
            Query presentQuery = NumericRangeQuery.newIntRange("present",
                    queryParams.getMinPresent(), queryParams.getMaxPresent(), true, true);
            query.add(presentQuery, Occur.MUST);
        }
        if (queryParams.getMinMissing() != null || queryParams.getMaxMissing() != null) {
            Query missingQuery = NumericRangeQuery.newIntRange("missing",
                    queryParams.getMinMissing(), queryParams.getMaxMissing(), true, true);
            query.add(missingQuery, Occur.MUST);
        }
        if (queryParams.getMinPercent() != null || queryParams.getMaxPercent() != null) {
            Query percentQuery = NumericRangeQuery.newIntRange("percent",
                    queryParams.getMinPercent(), queryParams.getMaxPercent(), true, true);
            query.add(percentQuery, Occur.MUST);
        }
    } catch (KeyNotFoundException e) {
        // No MP3 terms to include, return without amending query
    }
}
 
Example 6
Source File: LuceneQueryBuilder.java    From development with Apache License 2.0 6 votes vote down vote up
private static BooleanQuery prepareWildcardQueryForSingleToken(String token,
        List<String> fieldNames, String locale, String defaultLocale,
        boolean isDefaultLocaleHandling) {

    BooleanQuery queryPart = new BooleanQuery();

    for (String fieldName : fieldNames) {
        if (isDefaultLocaleHandling) {
            if (locale.equals(defaultLocale)) {
                throw new IllegalArgumentException(
                        "For default locale handling, locale and default locale must be different");
            }
            BooleanQuery localeHandlingQuery = constructDefaultLocaleHandlingQuery(
                    fieldName, locale, defaultLocale, token);
            queryPart.add(localeHandlingQuery, Occur.SHOULD);
        } else {
            WildcardQuery wildcardQuery = new WildcardQuery(new Term(
                    fieldName + locale, "*" + token.toLowerCase() + "*"));
            queryPart.add(wildcardQuery, Occur.SHOULD);
        }

    }
    return queryPart;
}
 
Example 7
Source File: LuceneSearcher.java    From uncc2014watsonsim with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a Lucene query using the bigrams in the given text
 * @param text
 */
public BooleanQuery queryFromSkipBigrams(String text) {
	BooleanQuery q = new BooleanQuery();
	String prev_word = null;
	for (String word : text.split("\\W+")) {
		if (prev_word != null) {
			PhraseQuery pq = new PhraseQuery();
			pq.setSlop(1);
			pq.add(new Term("text", prev_word));
			pq.add(new Term("text", word));
			q.add(pq, BooleanClause.Occur.SHOULD);
		}
		q.add(new TermQuery(new Term("text", word)), BooleanClause.Occur.SHOULD);
		prev_word = word;
	}
	return q;
}
 
Example 8
Source File: DBPediaCandidateType.java    From uncc2014watsonsim with GNU General Public License v2.0 6 votes vote down vote up
public List<String> query(String question_text) {
	List<String> results = new ArrayList<>();
	try {
		BooleanQuery q = new BooleanQuery();
		for (String word : question_text.split("\\W+")) {
			q.add(new TermQuery(new Term("text", word)), BooleanClause.Occur.SHOULD);
			q.add(new TermQuery(new Term("text", word.toLowerCase())), BooleanClause.Occur.SHOULD);
		}
		TopDocs topDocs = searcher.search(q, 1);
		
		ScoreDoc[] hits = topDocs.scoreDocs;
		// This isn't range based because we need the rank
		for (int i=0; i < hits.length; i++) {
			ScoreDoc s = hits[i];
			Document doc = searcher.doc(s.doc);
			results.add(doc.get("uri"));
		}
	} catch (IOException e) {
		System.out.println("Failed to query Lucene. Is the index in the correct location?");
		e.printStackTrace();
	}
	return results;
}
 
Example 9
Source File: SuperQueryTest.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
@Test
public void testConstantScoreTypes() throws Exception {
  IndexSearcher searcher = createSearcher();
  BooleanQuery booleanQuery = new BooleanQuery();
  booleanQuery.add(wrapSuper(PERSON_NAME, NAME1, ScoreType.CONSTANT), Occur.SHOULD);
  booleanQuery.add(wrapSuper(ADDRESS_STREET, STREET1, ScoreType.CONSTANT), Occur.MUST);
  TopDocs topDocs = searcher.search(booleanQuery, 10);
  assertEquals(3, topDocs.totalHits);
  printTopDocs(topDocs);
}
 
Example 10
Source File: AbstractIndexManager.java    From webdsl with Apache License 2.0 5 votes vote down vote up
protected static Query mustNotNamespaceQuery(String namespace) {
	BooleanQuery q = new BooleanQuery();
	q.add(new MatchAllDocsQuery(), Occur.SHOULD); // needed to perform a
													// must not query
	q.add(new TermQuery(new Term(SearchHelper.NAMESPACEFIELD, namespace)),
			Occur.MUST_NOT);
	return q;
}
 
Example 11
Source File: IMDBQueryExtension.java    From drftpd with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void addQueryTerms(BooleanQuery query, AdvancedSearchParams params) {
    try {
        IMDBQueryParams queryParams = params.getExtensionData(IMDBQueryParams.IMDBQUERYPARAMS);
        if (queryParams.getTitle() != null) {
            Query titleQuery = LuceneUtils.analyze("imdbtitle", TERM_TITLE, queryParams.getTitle());
            query.add(titleQuery, Occur.MUST);
        }
        if (queryParams.getDirector() != null) {
            Query directorQuery = LuceneUtils.analyze("imdbdirector", TERM_DIRECTOR, queryParams.getDirector());
            query.add(directorQuery, Occur.MUST);
        }
        if (queryParams.getGenres() != null) {
            Query genresQuery = LuceneUtils.analyze("imdbgenres", TERM_GENRES, queryParams.getGenres());
            query.add(genresQuery, Occur.MUST);
        }
        if (queryParams.getMinVotes() != null || queryParams.getMaxVotes() != null) {
            Query votesQuery = NumericRangeQuery.newIntRange("imdbvotes",
                    queryParams.getMinVotes(), queryParams.getMaxVotes(), true, true);
            query.add(votesQuery, Occur.MUST);
        }
        if (queryParams.getMinRating() != null || queryParams.getMaxRating() != null) {
            Query ratingQuery = NumericRangeQuery.newIntRange("imdbrating",
                    queryParams.getMinRating(), queryParams.getMaxRating(), true, true);
            query.add(ratingQuery, Occur.MUST);
        }
        if (queryParams.getMinYear() != null || queryParams.getMaxYear() != null) {
            Query yearQuery = NumericRangeQuery.newIntRange("imdbyear",
                    queryParams.getMinYear(), queryParams.getMaxYear(), true, true);
            query.add(yearQuery, Occur.MUST);
        }
        if (queryParams.getMinRuntime() != null || queryParams.getMaxRuntime() != null) {
            Query runtimeQuery = NumericRangeQuery.newIntRange("imdbruntime",
                    queryParams.getMinRuntime(), queryParams.getMaxRuntime(), true, true);
            query.add(runtimeQuery, Occur.MUST);
        }
    } catch (KeyNotFoundException e) {
        // No IMDB terms to include, return without amending query
    }
}
 
Example 12
Source File: QueryStringQueryConstructor.java    From linden with Apache License 2.0 5 votes vote down vote up
@Override
protected Query construct(LindenQuery lindenQuery, LindenConfig config) throws IOException {
  LindenQueryStringQuery stringQuery = lindenQuery.getQueryString();
  QueryParser.Operator op = QueryParser.Operator.OR;
  if (stringQuery.isSetOperator() && stringQuery.getOperator() == Operator.AND) {
    op = QueryParser.Operator.AND;
  }
  QueryParser queryParser = new LindenQueryParser(config);
  String content = stringQuery.getQuery();
  try {
    queryParser.setDefaultOperator(op);
    Query query = queryParser.parse(content);
    // disable coord
    if (query instanceof BooleanQuery) {
      BooleanQuery bQuery = (BooleanQuery) query;
      BooleanQuery booleanQuery = new BooleanQuery(stringQuery.isDisableCoord());
      BooleanClause[] clauses = bQuery.getClauses();
      for (BooleanClause clause : clauses) {
        booleanQuery.add(clause);
      }
      booleanQuery.setBoost(query.getBoost());
      query = booleanQuery;
    }
    return query;
  } catch (ParseException e) {
    throw new IOException(Throwables.getStackTraceAsString(e));
  }
}
 
Example 13
Source File: IndexManager.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
public static void populateSelector(IndexSearcherCloseable searcher, String shardName, String table, Selector selector)
    throws IOException {
  Tracer trace = Trace.trace("populate selector");
  String rowId = selector.rowId;
  String recordId = selector.recordId;
  try {
    BooleanQuery query = new BooleanQuery();
    if (selector.recordOnly) {
      query.add(new TermQuery(new Term(RECORD_ID, recordId)), Occur.MUST);
      query.add(new TermQuery(new Term(ROW_ID, rowId)), Occur.MUST);
    } else {
      query.add(new TermQuery(new Term(ROW_ID, rowId)), Occur.MUST);
      query.add(new TermQuery(BlurUtil.PRIME_DOC_TERM), Occur.MUST);
    }
    TopDocs topDocs = searcher.search(query, 1);
    if (topDocs.totalHits > 1) {
      if (selector.recordOnly) {
        LOG.warn("Rowid [" + rowId + "], recordId [" + recordId
            + "] has more than one prime doc that is not deleted.");
      } else {
        LOG.warn("Rowid [" + rowId + "] has more than one prime doc that is not deleted.");
      }
    }
    if (topDocs.totalHits == 1) {
      selector.setLocationId(shardName + "/" + topDocs.scoreDocs[0].doc);
    } else {
      selector.setLocationId(NOT_FOUND);
    }
  } finally {
    trace.done();
  }
}
 
Example 14
Source File: TestLuceneQueryTranslator.java    From imhotep with Apache License 2.0 5 votes vote down vote up
@Test
public void testNor() {
    final BooleanQuery bq = new BooleanQuery();
    bq.add(new TermQuery(new org.apache.lucene.index.Term("f", "a")), BooleanClause.Occur.MUST_NOT);
    bq.add(new TermQuery(new org.apache.lucene.index.Term("f", "b")), BooleanClause.Occur.MUST_NOT);

    Query q1 = LuceneQueryTranslator.rewrite(bq, Collections.<String>emptySet());
    assertEquals(Query.newBooleanQuery(BooleanOp.NOT, ImmutableList.of(
            Query.newBooleanQuery(BooleanOp.OR, ImmutableList.of(
                    Query.newTermQuery(new Term("f", false, 0, "a")),
                    Query.newTermQuery(new Term("f", false, 0, "b"))))
    )), q1);
}
 
Example 15
Source File: FlacQueryExtension.java    From drftpd with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void addQueryTerms(BooleanQuery query, AdvancedSearchParams params) {
    try {
        FlacQueryParams queryParams = params.getExtensionData(FlacQueryParams.FLACQUERYPARAMS);
        if (queryParams.getGenre() != null) {
            Query genreQuery = LuceneUtils.analyze("flacGenre", TERM_GENRE, queryParams.getGenre());
            query.add(genreQuery, Occur.MUST);
        }
        if (queryParams.getTitle() != null) {
            Query titleQuery = LuceneUtils.analyze("flacTitle", TERM_TITLE, queryParams.getTitle());
            query.add(titleQuery, Occur.MUST);
        }
        if (queryParams.getArtist() != null) {
            Query artistQuery = LuceneUtils.analyze("flacArtist", TERM_ARTIST, queryParams.getArtist());
            query.add(artistQuery, Occur.MUST);
        }
        if (queryParams.getAlbum() != null) {
            Query albumQuery = LuceneUtils.analyze("flacAlbum", TERM_ALBUM, queryParams.getAlbum());
            query.add(albumQuery, Occur.MUST);
        }
        if (queryParams.getMinYear() != null || queryParams.getMaxYear() != null) {
            Query yearQuery = NumericRangeQuery.newIntRange("flacYear",
                    queryParams.getMinYear(), queryParams.getMaxYear(), true, true);
            query.add(yearQuery, Occur.MUST);
        }
    } catch (KeyNotFoundException e) {
        // No FLAC terms to include, return without amending query
    }
}
 
Example 16
Source File: ArtifactDaoImpl.java    From artifact-listener with Apache License 2.0 5 votes vote down vote up
private FullTextQuery getSearchRecommendedQuery(String searchTerm) throws ServiceException {
	if (!StringUtils.hasText(searchTerm)) {
		return null;
	}
	FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(getEntityManager());
	
	QueryBuilder artifactQueryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder()
			.forEntity(Artifact.class).get();
	
	BooleanJunction<?> booleanJunction = artifactQueryBuilder.bool();
	
	booleanJunction.must(artifactQueryBuilder
			.keyword()
			.onField(Binding.artifact().deprecationStatus().getPath())
			.matching(ArtifactDeprecationStatus.NORMAL)
			.createQuery());
	
	try {
		searchTerm = LuceneUtils.getSimilarityQuery(searchTerm, 2);
		String[] fields = new String[] {
				Binding.artifact().artifactId().getPath(),
				Binding.artifact().group().groupId().getPath()
		};
		Analyzer analyzer = Search.getFullTextEntityManager(getEntityManager()).getSearchFactory().getAnalyzer(Artifact.class);
		
		MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);
		parser.setDefaultOperator(MultiFieldQueryParser.AND_OPERATOR);

		BooleanQuery booleanQuery = new BooleanQuery();
		booleanQuery.add(parser.parse(searchTerm), BooleanClause.Occur.MUST);
		
		booleanJunction.must(booleanQuery);
	} catch (ParseException e) {
		throw new ServiceException(String.format("Error parsing request: %1$s", searchTerm), e);
	}
	
	return fullTextEntityManager.createFullTextQuery(booleanJunction.createQuery(), Artifact.class);
}
 
Example 17
Source File: TestLuceneQueryTranslator.java    From imhotep with Apache License 2.0 5 votes vote down vote up
@Test
public void testMixed1() {
    final BooleanQuery bq = new BooleanQuery();
    bq.add(new TermQuery(new org.apache.lucene.index.Term("f", "a")), BooleanClause.Occur.MUST);
    bq.add(new TermQuery(new org.apache.lucene.index.Term("f", "b")), BooleanClause.Occur.SHOULD);

    Query q1 = LuceneQueryTranslator.rewrite(bq, Collections.<String>emptySet());
    assertEquals(Query.newBooleanQuery(BooleanOp.AND, ImmutableList.of(
            Query.newTermQuery(new Term("f", false, 0, "a"))
    )), q1);
}
 
Example 18
Source File: LuceneUtil.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public static org.apache.lucene.search.Query convertQuery(final org.apache.nifi.provenance.search.Query query) {
    if (query.getStartDate() == null && query.getEndDate() == null && query.getSearchTerms().isEmpty()) {
        return new MatchAllDocsQuery();
    }

    final BooleanQuery luceneQuery = new BooleanQuery();
    for (final SearchTerm searchTerm : query.getSearchTerms()) {
        final String searchValue = searchTerm.getValue();
        if (searchValue == null) {
            throw new IllegalArgumentException("Empty search value not allowed (for term '" + searchTerm.getSearchableField().getFriendlyName() + "')");
        }

        if (searchValue.contains("*") || searchValue.contains("?")) {
            luceneQuery.add(new BooleanClause(new WildcardQuery(new Term(searchTerm.getSearchableField().getSearchableFieldName(), searchTerm.getValue().toLowerCase())), Occur.MUST));
        } else {
            luceneQuery.add(new BooleanClause(new TermQuery(new Term(searchTerm.getSearchableField().getSearchableFieldName(), searchTerm.getValue().toLowerCase())), Occur.MUST));
        }
    }

    final Long minBytes = query.getMinFileSize() == null ? null : DataUnit.parseDataSize(query.getMinFileSize(), DataUnit.B).longValue();
    final Long maxBytes = query.getMaxFileSize() == null ? null : DataUnit.parseDataSize(query.getMaxFileSize(), DataUnit.B).longValue();
    if (minBytes != null || maxBytes != null) {
        luceneQuery.add(NumericRangeQuery.newLongRange(SearchableFields.FileSize.getSearchableFieldName(), minBytes, maxBytes, true, true), Occur.MUST);
    }

    final Long minDateTime = query.getStartDate() == null ? null : query.getStartDate().getTime();
    final Long maxDateTime = query.getEndDate() == null ? null : query.getEndDate().getTime();
    if (maxDateTime != null || minDateTime != null) {
        luceneQuery.add(NumericRangeQuery.newLongRange(SearchableFields.EventTime.getSearchableFieldName(), minDateTime, maxDateTime, true, true), Occur.MUST);
    }

    return luceneQuery;
}
 
Example 19
Source File: TvMazeQueryExtension.java    From drftpd with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void addQueryTerms(BooleanQuery query, AdvancedSearchParams params) {
    try {
        TvMazeQueryParams queryParams = params.getExtensionData(TvMazeQueryParams.TvMazeQUERYPARAMS);
        if (queryParams.getName() != null) {
            Query nameQuery = LuceneUtils.analyze("tvmazename", TERM_NAME, queryParams.getName());
            query.add(nameQuery, Occur.MUST);
        }
        if (queryParams.getGenre() != null) {
            Query genreQuery = LuceneUtils.analyze("tvmazegenre", TERM_GENRE, queryParams.getGenre());
            query.add(genreQuery, Occur.MUST);
        }
        if (queryParams.getSeason() != null) {
            Query seasonQuery = NumericRangeQuery.newIntRange("tvmazeseason",
                    queryParams.getSeason(), queryParams.getSeason(), true, true);
            query.add(seasonQuery, Occur.MUST);
        }
        if (queryParams.getNumber() != null) {
            Query numberQuery = NumericRangeQuery.newIntRange("tvmazenumber",
                    queryParams.getNumber(), queryParams.getNumber(), true, true);
            query.add(numberQuery, Occur.MUST);
        }
        if (queryParams.getType() != null) {
            Query typeQuery = LuceneUtils.analyze("tvmazetype", TERM_TYPE, queryParams.getType());
            query.add(typeQuery, Occur.MUST);
        }
        if (queryParams.getStatus() != null) {
            Query statusQuery = LuceneUtils.analyze("tvmazestatus", TERM_STATUS, queryParams.getStatus());
            query.add(statusQuery, Occur.MUST);
        }
        if (queryParams.getLanguage() != null) {
            Query languageQuery = LuceneUtils.analyze("tvmazelanguage", TERM_LANGUAGE, queryParams.getLanguage());
            query.add(languageQuery, Occur.MUST);
        }
        if (queryParams.getCountry() != null) {
            Query countryQuery = LuceneUtils.analyze("tvmazecountry", TERM_COUNTRY, queryParams.getCountry());
            query.add(countryQuery, Occur.MUST);
        }
        if (queryParams.getNetwork() != null) {
            Query networkQuery = LuceneUtils.analyze("tvmazenetwork", TERM_NETWORK, queryParams.getNetwork());
            query.add(networkQuery, Occur.MUST);
        }
    } catch (KeyNotFoundException e) {
        // No TvMaze terms to include, return without amending query
    }
}
 
Example 20
Source File: SearchService.java    From subsonic with GNU General Public License v3.0 4 votes vote down vote up
public SearchResult search(SearchCriteria criteria, List<MusicFolder> musicFolders, IndexType indexType) {
    SearchResult result = new SearchResult();
    int offset = criteria.getOffset();
    int count = criteria.getCount();
    result.setOffset(offset);

    IndexReader reader = null;
    try {
        reader = createIndexReader(indexType);
        Searcher searcher = new IndexSearcher(reader);
        Analyzer analyzer = new SubsonicAnalyzer();

        MultiFieldQueryParser queryParser = new MultiFieldQueryParser(LUCENE_VERSION, indexType.getFields(), analyzer, indexType.getBoosts());

        BooleanQuery query = new BooleanQuery();
        query.add(queryParser.parse(analyzeQuery(criteria.getQuery())), BooleanClause.Occur.MUST);

        List<SpanTermQuery> musicFolderQueries = new ArrayList<SpanTermQuery>();
        for (MusicFolder musicFolder : musicFolders) {
            if (indexType == ALBUM_ID3 || indexType == ARTIST_ID3) {
                musicFolderQueries.add(new SpanTermQuery(new Term(FIELD_FOLDER_ID, NumericUtils.intToPrefixCoded(musicFolder.getId()))));
            } else {
                musicFolderQueries.add(new SpanTermQuery(new Term(FIELD_FOLDER, musicFolder.getPath().getPath())));
            }
        }
        query.add(new SpanOrQuery(musicFolderQueries.toArray(new SpanQuery[musicFolderQueries.size()])), BooleanClause.Occur.MUST);

        TopDocs topDocs = searcher.search(query, null, offset + count);
        result.setTotalHits(topDocs.totalHits);

        int start = Math.min(offset, topDocs.totalHits);
        int end = Math.min(start + count, topDocs.totalHits);
        for (int i = start; i < end; i++) {
            Document doc = searcher.doc(topDocs.scoreDocs[i].doc);
            switch (indexType) {
                case SONG:
                case ARTIST:
                case ALBUM:
                    MediaFile mediaFile = mediaFileService.getMediaFile(Integer.valueOf(doc.get(FIELD_ID)));
                    addIfNotNull(mediaFile, result.getMediaFiles());
                    break;
                case ARTIST_ID3:
                    Artist artist = artistDao.getArtist(Integer.valueOf(doc.get(FIELD_ID)));
                    addIfNotNull(artist, result.getArtists());
                    break;
                case ALBUM_ID3:
                    Album album = albumDao.getAlbum(Integer.valueOf(doc.get(FIELD_ID)));
                    addIfNotNull(album, result.getAlbums());
                    break;
                default:
                    break;
            }
        }

    } catch (Throwable x) {
        LOG.error("Failed to execute Lucene search.", x);
    } finally {
        FileUtil.closeQuietly(reader);
    }
    return result;
}