Java Code Examples for org.apache.solr.client.solrj.SolrQuery#setHighlight()

The following examples show how to use org.apache.solr.client.solrj.SolrQuery#setHighlight() . 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: DefaultQueryParser.java    From dubbox with Apache License 2.0 6 votes vote down vote up
/**
 * Append highlighting parameters to
 * {@link org.apache.solr.client.solrj.SolrQuery}
 *
 * @param solrQuery
 * @param query
 */
protected void processHighlightOptions(SolrQuery solrQuery, HighlightQuery query) {
	if (query.hasHighlightOptions()) {
		HighlightOptions highlightOptions = query.getHighlightOptions();
		solrQuery.setHighlight(true);
		if (!highlightOptions.hasFields()) {
			solrQuery.addHighlightField(HighlightOptions.ALL_FIELDS.getName());
		} else {
			for (Field field : highlightOptions.getFields()) {
				solrQuery.addHighlightField(field.getName());
			}
			for (FieldWithHighlightParameters fieldWithHighlightParameters : highlightOptions
					.getFieldsWithHighlightParameters()) {
				addPerFieldHighlightParameters(solrQuery, fieldWithHighlightParameters);
			}
		}
		for (HighlightParameter option : highlightOptions.getHighlightParameters()) {
			addOptionToSolrQuery(solrQuery, option);
		}
		if (highlightOptions.hasQuery()) {
			solrQuery.add(HighlightParams.Q, getQueryString(highlightOptions.getQuery()));
		}
	}
}
 
Example 2
Source File: SolrFilterVisitor.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
public void apply(SolrQuery solrQuery, Filter filter) {
    visit(filter);
    solrQuery.addFilterQuery(queryBuilder.toString());

    List<LikeFilter> likeFilters = extractLikeFilters(filter);
    if (!likeFilters.isEmpty()) {
        solrQuery.addField("id");
        solrQuery.setHighlight(true);
        solrQuery.setHighlightFragsize(0);
        solrQuery.add("hl.q", "*" + likeFilters.get(0).getValue() + "*");
        for (LikeFilter likeFilter : likeFilters) {
            String fieldName = likeFilter.getProjection().getName();
            if(highlightFields.contains(fieldName)) {
                solrQuery.addHighlightField(fieldName);
            }
        }
    }
}
 
Example 3
Source File: ItemSearchServiceLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenSearchingWithHitHighlighting_thenKeywordsShouldBeHighlighted() throws Exception {
    itemSearchService.index("hm0001", "Brand1 Washing Machine", "Home Appliances", 100f);
    itemSearchService.index("hm0002", "Brand1 Refrigerator", "Home Appliances", 300f);
    itemSearchService.index("hm0003", "Brand2 Ceiling Fan", "Home Appliances", 200f);
    itemSearchService.index("hm0004", "Brand2 Dishwasher", "Washing equipments", 250f);

    SolrQuery query = new SolrQuery();
    query.setQuery("Appliances");
    query.setHighlight(true);
    query.addHighlightField("category");
    query.setHighlightSimplePre("<strong>");
    query.setHighlightSimplePost("</strong>");
    QueryResponse response = solrClient.query(query);

    Map<String, Map<String, List<String>>> hitHighlightedMap = response.getHighlighting();
    Map<String, List<String>> highlightedFieldMap = hitHighlightedMap.get("hm0001");
    List<String> highlightedList = highlightedFieldMap.get("category");
    String highLightedText = highlightedList.get(0);

    assertEquals("Home <strong>Appliances</strong>", highLightedText);

}
 
Example 4
Source File: SearchServiceImpl.java    From learning-taotaoMall with MIT License 5 votes vote down vote up
@Override
public SearchResult search(String queryString, int page, int rows) throws Exception {
	//创建查询对象
	SolrQuery query = new SolrQuery();
	//设置查询条件
	query.setQuery(queryString);
	//设置分页
	query.setStart((page - 1) * rows);
	query.setRows(rows);
	//设置默认搜素域
	query.set("df", "item_keywords");
	//设置高亮显示
	query.setHighlight(true);
	query.addHighlightField("item_title");
	query.setHighlightSimplePre("<em style=\"color:red\">");
	query.setHighlightSimplePost("</em>");
	//执行查询
	SearchResult searchResult = searchDao.search(query);
	//计算查询结果总页数
	long recordCount = searchResult.getRecordCount();
	long pageCount = recordCount / rows;
	if (recordCount % rows > 0) {
		pageCount++;
	}
	searchResult.setPageCount(pageCount);
	searchResult.setCurPage(page);

	return searchResult;
}
 
Example 5
Source File: SearchITCase.java    From apache-solr-essentials with Apache License 2.0 5 votes vote down vote up
/**
 * Selects all documents using an handler configured with SolrQueryParser
 * 
 * @throws Exception hopefully never, otherwise the test fails.
 */
@Test
public void selectAll() throws Exception {
	// 1. Prepare the Query object
	// The query string can be directly injected in the constructor
	final SolrQuery query = new SolrQuery("*:*");
	query.setRequestHandler("/h1");
	
	// These settings will override the "defaults" section
	query.setFacet(false);
	query.setHighlight(false);
	query.setSort("released", ORDER.desc);
	
	// We are asking 5 documents per page
	query.setRows(5);
	
	// 2. Send the query request and get the corresponding response.
	final QueryResponse response = SEARCHER.query(query);
	
	// 3. Get the result object, containing documents and metadata.
	final SolrDocumentList documents = response.getResults();
	
	// If not explicitly requested (or set in the handler) the start is set to 0
	assertEquals(0, documents.getStart());
	
	// Total number of documents found must be equals to all documents we previously indexed
	assertEquals(sampleData().size(), documents.getNumFound());
	
	// Page size must be 5, as requested
	assertEquals(5, documents.size());
}
 
Example 6
Source File: SolrController.java    From Spring-Boot-Book with Apache License 2.0 4 votes vote down vote up
@RequestMapping("/queryAll")
    public Object queryAll() throws IOException, SolrServerException {


        //第二种方式
        SolrQuery solrQuery = new SolrQuery();
        // 设置默认搜索域
        solrQuery.setQuery("*:*");
//        solrQuery.addField("*");
        solrQuery.set("q", "知然");
        solrQuery.add("q", "name:然");
        // 设置返回结果的排序规则
        solrQuery.setSort("id", SolrQuery.ORDER.asc);
        //设置查询的条数
        solrQuery.setRows(50);
        //设置查询的开始
        solrQuery.setStart(0);
        // 设置分页参数
        solrQuery.setStart(0);
        solrQuery.setRows(20);
        //设置高亮
        solrQuery.setHighlight(true);
        //设置高亮的字段
        solrQuery.addHighlightField("name");
        //设置高亮的样式
        solrQuery.setHighlightSimplePre("<font color='red'>");
        solrQuery.setHighlightSimplePost("</font>");
        System.out.println(solrQuery);
        QueryResponse response = solrClient.query(solrQuery);
        //返回高亮显示结果
        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
        //response.getResults();查询返回的结果

        SolrDocumentList documentList = response.getResults();
        long numFound = documentList.getNumFound();
        System.out.println("总共查询到的文档数量: " + numFound);
        for (SolrDocument solrDocument : documentList) {
            System.out.println("solrDocument==============" + solrDocument);
            System.out.println("solrDocument==============" + solrDocument.get("name"));
        }
        return highlighting;
    }
 
Example 7
Source File: SolrControllerTest.java    From Spring-Boot-Book with Apache License 2.0 4 votes vote down vote up
@Test
    public void queryAll() throws IOException, SolrServerException {


        //第二种方式
        SolrQuery solrQuery = new SolrQuery();
        // 设置默认搜索域
        solrQuery.setQuery("*:*");
//        solrQuery.addField("*");
        solrQuery.set("q", "知然");
        solrQuery.add("q", "name:然");
        // 设置返回结果的排序规则
        solrQuery.setSort("id", SolrQuery.ORDER.asc);
        //设置查询的条数
        solrQuery.setRows(50);
        //设置查询的开始
        solrQuery.setStart(0);
        // 设置分页参数
        solrQuery.setStart(0);
        solrQuery.setRows(20);
        //设置高亮
        solrQuery.setHighlight(true);
        //设置高亮的字段
        solrQuery.addHighlightField("name");
        //设置高亮的样式
        solrQuery.setHighlightSimplePre("<font color='red'>");
        solrQuery.setHighlightSimplePost("</font>");
        System.out.println(solrQuery);
        QueryResponse response = solrClient.query(solrQuery);
        //返回高亮显示结果
        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
        //response.getResults();查询返回的结果

        SolrDocumentList documentList = response.getResults();
        long numFound = documentList.getNumFound();
        System.out.println("总共查询到的文档数量: " + numFound);
        for (SolrDocument solrDocument : documentList) {
            System.out.println(solrDocument);
            System.out.println(solrDocument.get("name"));
        }
        System.out.println(highlighting);
    }
 
Example 8
Source File: TestTolerantSearch.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public void testGetFieldsPhaseError() throws SolrServerException, IOException {
  BadResponseWriter.failOnGetFields = true;
  BadResponseWriter.failOnGetTopIds = false;
  SolrQuery query = new SolrQuery();
  query.setQuery("subject:batman OR subject:superman");
  query.addField("id");
  query.addField("subject");
  query.set("distrib", "true");
  query.set("shards", shard1 + "," + shard2);
  query.set(ShardParams.SHARDS_INFO, "true");
  query.set("debug", "true");
  query.set("stats", "true");
  query.set("stats.field", "id");
  query.set("mlt", "true");
  query.set("mlt.fl", "title");
  query.set("mlt.count", "1");
  query.set("mlt.mintf", "0");
  query.set("mlt.mindf", "0");
  query.setHighlight(true);
  query.addFacetField("id");
  query.setFacet(true);
  
  ignoreException("Dummy exception in BadResponseWriter");

  expectThrows(SolrException.class, () -> collection1.query(query));

  query.set(ShardParams.SHARDS_TOLERANT, "true");
  QueryResponse response = collection1.query(query);
  assertTrue(response.getResponseHeader().getBooleanArg(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY));
  NamedList<Object> shardsInfo = ((NamedList<Object>)response.getResponse().get(ShardParams.SHARDS_INFO));
  boolean foundError = false;
  for (int i = 0; i < shardsInfo.size(); i++) {
    if (shardsInfo.getName(i).contains("collection2")) {
      assertNotNull(((NamedList<Object>)shardsInfo.getVal(i)).get("error"));
      foundError = true;
      break;
    }
  }
  assertTrue(foundError);
  assertEquals("1", response.getResults().get(0).getFieldValue("id"));
  assertEquals("batman", response.getResults().get(0).getFirstValue("subject"));
  unIgnoreException("Dummy exception in BadResponseWriter");
}
 
Example 9
Source File: TestTolerantSearch.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public void testGetTopIdsPhaseError() throws SolrServerException, IOException {
  BadResponseWriter.failOnGetTopIds = true;
  BadResponseWriter.failOnGetFields = false;
  SolrQuery query = new SolrQuery();
  query.setQuery("subject:batman OR subject:superman");
  query.addField("id");
  query.addField("subject");
  query.set("distrib", "true");
  query.set("shards", shard1 + "," + shard2);
  query.set(ShardParams.SHARDS_INFO, "true");
  query.set("debug", "true");
  query.set("stats", "true");
  query.set("stats.field", "id");
  query.set("mlt", "true");
  query.set("mlt.fl", "title");
  query.set("mlt.count", "1");
  query.set("mlt.mintf", "0");
  query.set("mlt.mindf", "0");
  query.setHighlight(true);
  query.addFacetField("id");
  query.setFacet(true);
  
  ignoreException("Dummy exception in BadResponseWriter");

  expectThrows(Exception.class, () -> collection1.query(query));

  query.set(ShardParams.SHARDS_TOLERANT, "true");
  QueryResponse response = collection1.query(query);
  assertTrue(response.getResponseHeader().getBooleanArg(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY));
  NamedList<Object> shardsInfo = ((NamedList<Object>)response.getResponse().get(ShardParams.SHARDS_INFO));
  boolean foundError = false;
  for (int i = 0; i < shardsInfo.size(); i++) {
    if (shardsInfo.getName(i).contains("collection2")) {
      assertNotNull(((NamedList<Object>)shardsInfo.getVal(i)).get("error"));
      foundError = true;
      break;
    }
  }
  assertTrue(foundError);
  assertFalse(""+response, response.getResults().isEmpty());
  assertEquals("1", response.getResults().get(0).getFieldValue("id"));
  assertEquals("batman", response.getResults().get(0).getFirstValue("subject"));
  unIgnoreException("Dummy exception in BadResponseWriter");
}
 
Example 10
Source File: SearchITCase.java    From apache-solr-essentials with Apache License 2.0 4 votes vote down vote up
/**
 * Demonstrates how to ask for faceting and iterate over response facets.
 * 
 * @throws Exception hopefully never, otherwise the test fails.
 */
@Test
public void facets() throws Exception {
	// 1. Prepare the Query object
	// The query string can be directly injected in the constructor
	final SolrQuery query = new SolrQuery("*:*");
	query.setRequestHandler("/h1");
	
	// These settings will override the "defaults" section
	// Note that this handler sets facet to true, so the following line is
	// not actually needed
	query.setFacet(true);
	query.addFacetField("genre", "released");
	
	// We don't want highlighting here
	// Since the HL component is disabled by default, also this line is not needed.
	query.setHighlight(false);
	
	// We are only interested in facets, so skip don't include any 
	// document in the response.
	query.setRows(0);
	
	// 2. Send the query request and get the corresponding response.
	final QueryResponse response = SEARCHER.query(query);
	
	// 3. Get the result object, containing documents and metadata.
	final SolrDocumentList documents = response.getResults();
	
	// If not explicitly requested (or set in the handler) the start is set to 0
	assertEquals(0, documents.getStart());
	
	// Total number of documents found must be equals to all documents we previously indexed
	assertEquals(sampleData().size(), documents.getNumFound());
	
	// Page size must be 0, as requested
	assertEquals(0, documents.size());
	
	final FacetField genre = response.getFacetField("genre");
	assertNotNull(genre);
	 
	// This is something that should never appear within a TestCase :) 
	// however is useful to demonstrate how to iterate over facet values
	for (final Count count : genre.getValues()) {
		// e.g. Jazz : 19
		// e.g. Fusion: 11
		System.out.println(count.getName() + " : " + count.getCount());
	}
}