@Test
  public void testFilenameNumberedDelimiterDash() throws Exception {
    SolrServer solr = getSolr();
    SolrInputDocument doc1 = new SolrInputDocument();
    doc1.addField("id", "1");
    doc1.addField("pathnamebase", "MAP-12345678");
    solr.add(doc1);
    SolrInputDocument doc2 = new SolrInputDocument();
    doc2.addField("id", "2");
    doc2.addField("pathnamebase", "TOP-12345678");
    solr.add(doc2);
    solr.commit();

    assertEquals(
        "exact match",
        1,
        solr.query(new SolrQuery("name:MAP-12345678")).getResults().getNumFound());
    assertEquals(
        "exact match",
        1,
        solr.query(new SolrQuery("name:TOP-12345678")).getResults().getNumFound());
    // split on dash
    assertEquals(
        "split on dash", 1, solr.query(new SolrQuery("name:TOP")).getResults().getNumFound());
    assertEquals(
        "split on dash", 2, solr.query(new SolrQuery("name:12345678")).getResults().getNumFound());
    assertEquals(
        "split on dash",
        1,
        solr.query(new SolrQuery("name:TOP 12345678")).getResults().getNumFound());
  }
  /**
   * Query the indexed csv data using Tabular query, with the parameter {@link SirenParams#TQ}.
   *
   * @throws SolrServerException
   */
  public void query() throws SolrServerException {
    System.out.println("Query: [0]'conference1'");
    final SolrQuery query1 = new SolrQuery();
    query1.setQueryType("siren");
    query1.set(SirenParams.TQ, "[0]'conference1'"); // tabular query
    final QueryResponse response1 = server.query(query1);
    for (SolrDocument d : response1.getResults()) {
      System.out.println(d);
    }
    System.out.println();

    System.out.println("Query: * <name> 'john AND gartner'");
    final SolrQuery query2 = new SolrQuery();
    query2.setQueryType("siren");
    query2.set(SirenParams.NQ, "* <name> 'john AND gartner'"); // ntriple query
    final QueryResponse response2 = server.query(query2);
    for (SolrDocument d : response2.getResults()) {
      System.out.println(d);
    }
    System.out.println();

    System.out.println("Query: * <type> <student> AND [2]'[* TO 2010]'^^<xsd:int>");
    final SolrQuery query3 = new SolrQuery();
    query3.setQueryType("siren");
    query3.set(SirenParams.NQ, "* <type> <student>"); // ntriple query
    query3.set(SirenParams.TQ, "[2]'[* TO 2010]'^^<xsd:int>"); // tabular query
    final QueryResponse response3 = server.query(query3);
    for (SolrDocument d : response3.getResults()) {
      System.out.println(d);
    }
    System.out.println();
  }
  @Test
  public void testFulltextSearchEmail() throws Exception {
    SolrServer solr = getSolr();
    SolrInputDocument doc = new SolrInputDocument();
    doc.addField("id", "1");
    doc.addField("text", "contact [email protected]");
    solr.add(doc);
    solr.commit();

    assertEquals(
        "Should match simple word",
        1,
        solr.query(new SolrQuery("text:contact")).getResults().getNumFound());
    // Likely NOT possible with WDF in index pipeline.
    assertEquals(
        "Should match exact email",
        1,
        solr.query(new SolrQuery("text:[email protected]")).getResults().getNumFound());
    assertEquals(
        "Should match exact email - Quoted",
        1,
        solr.query(new SolrQuery("text:\"[email protected]\"")).getResults().getNumFound());

    assertEquals(
        "Could match part 1",
        1,
        solr.query(new SolrQuery("text:support")).getResults().getNumFound());
    assertEquals(
        "Could match part 2",
        1,
        solr.query(new SolrQuery("text:example.com")).getResults().getNumFound());
  }
Exemplo n.º 4
0
  public SolrDocumentList runQuery(
      String q,
      int results,
      String type,
      String mm,
      String Geneboost,
      String Diseboost,
      String Verbboost)
      throws SolrServerException {
    SolrQuery query = new SolrQuery();
    if (type.equals("dismax")) {
      query.setParam("defType", "edismax");
      query.setParam("qf", "text");
      query.setParam("mm", mm);
      query.setParam("pf", "text^100");
    }

    query.setQuery(getBoosts(escapeQuery(q), Geneboost, Diseboost, Verbboost));
    query.setRows(results);
    query.setFields("*", "score");
    // can also try nested query for different boosts of phrase in text
    // q=revised+AND+book+AND+_query_:"{!dismax qf=title pf=title^10 v=$qq}"&qq=revised+book

    System.out.println(query.toString());

    QueryResponse rsp = server.query(query);
    return rsp.getResults();
  }
 @Test(dependsOnMethods = "testAddDocument")
 public void testBasicQuery() throws SolrServerException {
   SolrServer server = solrServerFactory.getServer();
   SolrParams params = new SolrQuery("*:*");
   SolrDocumentList results = server.query(params).getResults();
   assertTrue(results.getNumFound() > 0, "didn't return any results");
 }
Exemplo n.º 6
0
  public List<DOSearchResult> getSearchResults(
      DORestSearchRequest request, SearchErrors errors, Map<String, ArrayList<String>> nerMap) {
    List<DOSearchResult> result = new ArrayList<DOSearchResult>();
    QueryParam tcqp = null;
    QueryResponse qres = null;
    try {
      SolrServer server = solrConnectionUtils.getRestSolrServer();

      tcqp = restQueryCreator.getSearchQuery(request, nerMap);
      qres = server.query(tcqp);
      if (qres != null) {
        DOSearchResult serachRes = null;
        if (request.isGrouprequest()) {
          serachRes =
              DOResponseUtils.processGroupQueryResponse(
                  qres, Constants.RESPONSE_TYPE_REST, request.isSpellcheckApplied());
        } else {
          serachRes =
              DOResponseUtils.processQueryResponse(
                  qres, Constants.RESPONSE_TYPE_REST, request.isSpellcheckApplied());
        }
        result.add(serachRes);
      }
    } catch (SolrServerException e) {
      logger.error(e.getMessage(), e);
      SearchError error = new SearchError(ErrorCode.SOLR_ERROR_CODE, e.getMessage());
      errors.add(error);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      SearchError error = new SearchError(ErrorCode.SOLR_ERROR_CODE, e.getMessage());
      errors.add(error);
    }

    return result;
  }
  @Test
  public void fieldsRequestsShouldTurnIntoSelectors() throws Exception, TException {

    String table = "fieldsRequestsShouldTurnIntoSelectors";
    SolrServer server =
        TestTableCreator.newTable(table)
            .withRowCount(1)
            .withRecordsPerRow(2)
            .withRecordColumns("fam.value", "fam.mvf")
            .create();

    SolrQuery query = new SolrQuery("value0-0");
    query.setFields("fam.value");
    QueryResponse response = server.query(query);

    assertEquals(
        "We should get our doc back for a valid test.", 1l, response.getResults().getNumFound());

    SolrDocument docResult = response.getResults().get(0);

    assertEquals("value0-0", docResult.getFieldValue("fam.value"));
    assertNull(
        "We shouldn't get this one back since it wasnt in our fields.",
        docResult.getFieldValues("fam.mvf"));

    removeTable(table);
  }
  @Test
  public void basicFullTextQuery() throws Exception {
    String table = "basicFullTextQuery";
    SolrServer server =
        TestTableCreator.newTable(table)
            .withRowCount(1)
            .withRecordsPerRow(2)
            .withRecordColumns("fam.value", "fam.mvf", "fam.mvf")
            .create();

    SolrQuery query = new SolrQuery("value0-0");

    QueryResponse response = server.query(query);

    assertEquals("We should get our doc back.", 1l, response.getResults().getNumFound());

    SolrDocument docResult = response.getResults().get(0);

    assertEquals("0", docResult.getFieldValue("recordid"));
    assertEquals("value0-0", docResult.getFieldValue("fam.value"));

    Collection<Object> mvfVals = docResult.getFieldValues("fam.mvf");

    assertTrue(
        "We should get all our values back[" + mvfVals + "]",
        CollectionUtils.isEqualCollection(mvfVals, Lists.newArrayList("value0-0", "value0-0")));

    removeTable(table);
  }
Exemplo n.º 9
0
  @RequestMapping("/search/{categoryId}")
  public String list(@PathVariable String categoryId, ModelMap model)
      throws SolrServerException, ParseException {
    SolrQuery query = new SolrQuery();

    query.setQuery("categoryId:" + categoryId);
    query.setRows(20);
    SolrDocumentList docs = solrServer.query(query).getResults();
    List<Article> articles = new ArrayList<Article>();
    for (SolrDocument solrDocument : docs) {
      Article article = new Article();
      article.setTitle(String.valueOf(solrDocument.getFieldValue("title")));
      article.setContent(String.valueOf(solrDocument.getFieldValue("content")));

      /** solr时间格式转换的坑,具体可参考 http://chengqianl.iteye.com/blog/1340385 */
      article.setCreateDate(
          new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
              .parse(String.valueOf(solrDocument.getFieldValue("createDate"))));
      articles.add(article);
    }

    model.addAttribute("articles", articles);

    return "/client/article/list";
  }
Exemplo n.º 10
0
  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;
  }
  private SearchEngineResponse<MediaItem> search(SolrQuery query) {

    SearchEngineResponse<MediaItem> response = new SearchEngineResponse<MediaItem>();
    QueryResponse rsp;

    try {
      rsp = server.query(query);
    } catch (SolrServerException e) {
      e.printStackTrace();
      Logger.getRootLogger().info(e.getMessage());
      return null;
    }

    List<SolrMediaItem> solrItems = rsp.getBeans(SolrMediaItem.class);

    List<MediaItem> mediaItems = new ArrayList<MediaItem>();
    for (SolrMediaItem solrMediaItem : solrItems) {
      try {
        MediaItem mediaItem = solrMediaItem.toMediaItem();
        String id = mediaItem.getId();

        mediaItem.setId(id);

        mediaItems.add(mediaItem);
      } catch (MalformedURLException ex) {
        Logger.getRootLogger().error(ex.getMessage());
      }
    }

    response.setResults(mediaItems);

    return response;
  }
Exemplo n.º 12
0
  public static void main(String a[]) throws MalformedURLException, SolrServerException {
    SolrServer hotServer = new CommonsHttpSolrServer("http://indexedsearch.prod.o.com:8980/cds");
    SolrQuery solrLocrQuery = new SolrQuery();
    /*solrLocrQuery.setParam("pos", "ORB");
    solrLocrQuery.setParam("locale", "en_US");*/
    solrLocrQuery.setRows(300);
    QueryResponse queryLocResponse = hotServer.query(solrLocrQuery);
    SolrDocumentList locList = queryLocResponse.getResults();

    for (SolrDocument doc : locList) {
      try {
        String str = doc.get("text_s").toString();
        if (str.toLowerCase().contains("price")) {
          if (str.toLowerCase().contains("assurance")) {
            String id = doc.get("id").toString();
            String url = doc.get("title_s").toString();

            System.out.println(id + "|" + url);
          }
        }
      } catch (Exception e) {

      }
    }
  }
 @Test(dependsOnMethods = {"testGetServer"})
 public void testBadQuery() throws SolrServerException {
   SolrServer server = solrServerFactory.getServer();
   SolrParams params = new SolrQuery("text that is not found");
   QueryResponse response = server.query(params);
   assertEquals(0L, response.getResults().getNumFound());
 }
 protected SolrDocumentList getSolrDocumentByUUIDs(List<String> uuids) {
   String operand = "OR";
   SolrDocumentList solrDocumentList = null;
   StringBuffer sb = new StringBuffer();
   sb.append("(");
   for (String uuid : uuids) {
     sb.append("(");
     sb.append(uuid);
     sb.append(")");
     sb.append(operand);
   }
   String queryString = sb.substring(0, sb.length() - operand.length()) + ")";
   SolrQuery query = new SolrQuery();
   SolrDocument solrDocument = null;
   try {
     SolrServer server = SolrServerManager.getInstance().getSolrServer();
     QueryResponse response = null;
     query.setQuery("id:" + queryString);
     response = server.query(query);
     solrDocumentList = response.getResults();
   } catch (SolrServerException e) {
     LOG.info("Exception :", e);
     throw new DocstoreIndexException();
   }
   return solrDocumentList;
 }
Exemplo n.º 15
0
  @Test
  public void testClearDerefMap() throws Exception {
    DerefMap derefMap =
        DerefMapHbaseImpl.create(
            INDEX_NAME, lilyProxy.getHBaseProxy().getConf(), null, repository.getIdGenerator());

    Record linkedRecord =
        repository
            .recordBuilder()
            .id("deref-test-linkedrecord")
            .recordType(rt1.getName())
            .field(ft1.getName(), "deref test linkedrecord")
            .create();

    Record record =
        repository
            .recordBuilder()
            .id("deref-test-main")
            .recordType(rt1.getName())
            .field(ft1.getName(), "deref test main")
            .field(ft2.getName(), new Link(linkedRecord.getId()))
            .create();

    SchemaId vtag = typeManager.getFieldTypeByName(VersionTag.LAST).getId();
    DependantRecordIdsIterator it = null;

    try {
      it = derefMap.findDependantsOf(linkedRecord.getId(), ft1.getId(), vtag);
      assertTrue(!it.hasNext());
    } finally {
      it.close();
    }

    setBatchIndexConf(
        getResourceAsByteArray("batchIndexConf-testClearDerefmap-false.json"), null, false);

    buildAndCommit();

    QueryResponse response = solrServer.query(new SolrQuery("field1:deref\\ test\\ main"));
    assertEquals(1, response.getResults().size());

    try {
      it = derefMap.findDependantsOf(linkedRecord.getId(), ft1.getId(), vtag);
      assertTrue(it.hasNext());
    } finally {
      it.close();
    }

    setBatchIndexConf(
        null, getResourceAsByteArray("batchIndexConf-testClearDerefmap-true.json"), true);
    waitForIndexAndCommit(BUILD_TIMEOUT);

    try {
      it = derefMap.findDependantsOf(linkedRecord.getId(), ft1.getId(), vtag);
      assertTrue(!it.hasNext());
    } finally {
      it.close();
    }
  }
 @Test(dependsOnMethods = "testBasicQuery", dataProvider = "documentMap")
 public void testIdQuery(Map<String, String[]> document) throws SolrServerException {
   String id = document.get("id")[0];
   SolrServer server = solrServerFactory.getServer();
   SolrParams params = new SolrQuery("id:" + id);
   SolrDocumentList results = server.query(params).getResults();
   assertEquals(results.getNumFound(), 1, "didn't find article by id");
 }
Exemplo n.º 17
0
 protected void assertQueryError(String error, String query) throws SolrServerException {
   SolrQuery q = new SolrQuery(query);
   q.setRequestHandler(SOLR_QUERY_TYPE);
   QueryResponse rsp = solr.query(q, METHOD.POST);
   String actualError = rsp.getResponse().get("xpath-error").toString();
   assertTrue(
       "Error " + actualError + " does not contain expected error " + error,
       actualError.contains(error));
 }
Exemplo n.º 18
0
  public JSONArray Search(String query, String sort) {
    SolrServer server;
    SolrDocumentList docs = null;
    String Date_format = null; // for Date格式轉換
    JSONArray jsonArray = new JSONArray();
    try {
      server = new HttpSolrServer(url);
      // add

      SolrQuery solrQuery = new SolrQuery();
      solrQuery.setQuery(query);
      solrQuery.setStart(_start);
      solrQuery.setRows(_nbDocuments);
      solrQuery.setRequestHandler("query");
      solrQuery.set("fl", "*,score"); // 設定fl參數,指定要傳回哪個field的資料,這裡設定所有field與score
      if (_fq1 != "") {
        solrQuery.addFilterQuery("ProductName:" + _fq1);
      }
      if (_fq2 != "") {
        solrQuery.addFilterQuery("publishedDate:" + _fq2);
      }
      if (sort != null) {
        solrQuery.addSortField(sort, ORDER.asc);
      }
      solrQuery.setRequestHandler("/browse");
      response = server.query(solrQuery);
      docs = response.getResults();
      if (docs != null) {
        System.out.println(
            docs.getNumFound() + " documents found, " + docs.size() + " returned : ");
        setResultNumber(docs.getNumFound(), docs.size()); // 設定目前回傳幾筆資料給前端
        for (int i = 0; i < docs.size(); i++) {
          SolrDocument doc = docs.get(i);
          JSONObject jsonObject = new JSONObject();
          for (Iterator<Entry<String, Object>> it2 = doc.iterator(); it2.hasNext(); ) {
            Entry<String, Object> entry = it2.next();
            if (entry.getKey().equals("publishedDate")) { // 將傳回的date格式轉為純字串,方便前端呈現
              Date_format = entry.getValue().toString();
              jsonObject.put(entry.getKey(), Date_format);
            } else {
              // 一般情況
              jsonObject.put(entry.getKey(), entry.getValue());
            }
          }
          System.out.print("\n");
          // 將總共找到幾筆資料存在jsonarray的最後面傳給前端
          jsonObject.put("TotalResultFound", docs.getNumFound());
          jsonArray.add(jsonObject);
        }
      }

    } catch (SolrServerException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return jsonArray;
  }
Exemplo n.º 19
0
  public SolrDocumentList runQuery(String q, int results) throws SolrServerException {
    SolrQuery query = new SolrQuery();
    query.setQuery(escapeQuery(q));
    query.setRows(results);
    query.setFields("*", "score");
    System.out.println(query.toString());

    QueryResponse rsp = server.query(query);
    return rsp.getResults();
  }
Exemplo n.º 20
0
 public static SolrDocumentList query(SolrServer server, SolrQuery solrParams)
     throws DSpaceSolrException {
   try {
     solrParams.addSortField("item.id", ORDER.asc);
     QueryResponse response = server.query(solrParams);
     return response.getResults();
   } catch (SolrServerException ex) {
     throw new DSpaceSolrException(ex.getMessage(), ex);
   }
 }
Exemplo n.º 21
0
 public static SolrDocument querySingle(SolrServer server, SolrQuery solrParams)
     throws SolrSearchEmptyException {
   try {
     solrParams.addSortField("item.id", ORDER.asc);
     QueryResponse response = server.query(solrParams);
     if (response.getResults().getNumFound() > 0) return response.getResults().get(0);
     else throw new SolrSearchEmptyException();
   } catch (SolrServerException ex) {
     throw new SolrSearchEmptyException(ex.getMessage(), ex);
   }
 }
Exemplo n.º 22
0
 /**
  * Execute a search query
  *
  * @param solrQuery The solr query to perform
  * @param hasFacet Indicates whether the solr query has facets
  * @return The search result
  * @throws SolrServerException
  */
 private SolrSearchResult executeSearch(SolrQuery solrQuery, boolean hasFacet)
     throws SolrServerException {
   LOGGER.debug("Query to send to Solr: {}", solrQuery.toString());
   SolrServer solrServer = SolrManager.getInstance().getSolrServer();
   QueryResponse queryResponse = solrServer.query(solrQuery);
   if (hasFacet) {
     return new SolrSearchResult(queryResponse.getResults(), queryResponse.getFacetFields());
   } else {
     return new SolrSearchResult(queryResponse.getResults());
   }
 }
  @Test
  public void testFulltextSearchNumbers() throws Exception {
    SolrServer solr = getSolr();
    SolrInputDocument doc = new SolrInputDocument();
    doc.addField("id", "1");
    doc.addField("text", "word The SD500 product");
    solr.add(doc);
    solr.commit();

    assertEquals(
        "Should match simple word",
        1,
        solr.query(new SolrQuery("text:word")).getResults().getNumFound());
    assertEquals(
        "Should match exact product",
        1,
        solr.query(new SolrQuery("text:SD500")).getResults().getNumFound());
    assertEquals(
        "Should match exact product lowercase",
        1,
        solr.query(new SolrQuery("text:sd500")).getResults().getNumFound());
    assertEquals(
        "Should match exact product quoted",
        1,
        solr.query(new SolrQuery("text:\"SD500\"")).getResults().getNumFound());
    assertEquals(
        "Should match exact product wildcard",
        1,
        solr.query(new SolrQuery("text:SD5*")).getResults().getNumFound());

    // WDF needs splitOnNumerics for these, which requires catenate or preserve for above asserts.
    /*
    assertEquals("Could match part 1", 1, solr.query(new SolrQuery("text:SD")).getResults().getNumFound());
    assertEquals("Could match part 2", 1, solr.query(new SolrQuery("text:500")).getResults().getNumFound());
    */

    // These asserts document the desire to have less spurious hits
    assertEquals(
        "Avoid matching other product SD200",
        0,
        solr.query(new SolrQuery("text:SD200")).getResults().getNumFound());
    assertEquals(
        "Avoid matching other product XX500",
        0,
        solr.query(new SolrQuery("text:XX500")).getResults().getNumFound());

    assertEquals(
        "Should match quoted context",
        1,
        solr.query(new SolrQuery("text:\"The SD500 product\"")).getResults().getNumFound());
  }
  @Test
  public void testFulltextSearchNumbersHyphen() throws Exception {
    SolrServer solr = getSolr();
    SolrInputDocument doc = new SolrInputDocument();
    doc.addField("id", "1");
    doc.addField("text", "word The SD-500 product");
    solr.add(doc);
    solr.commit();

    assertEquals(
        "Should match simple word",
        1,
        solr.query(new SolrQuery("text:word")).getResults().getNumFound());
    assertEquals(
        "Should match exact product",
        1,
        solr.query(new SolrQuery("text:SD-500")).getResults().getNumFound());
    assertEquals(
        "Should match exact product lowercase",
        1,
        solr.query(new SolrQuery("text:sd-500")).getResults().getNumFound());

    // With hyphen also the StandardTokenizer will split.
    assertEquals(
        "Could match part 1", 1, solr.query(new SolrQuery("text:SD")).getResults().getNumFound());
    assertEquals(
        "Could match part 2", 1, solr.query(new SolrQuery("text:500")).getResults().getNumFound());

    assertEquals(
        "Could match quoted context",
        1,
        solr.query(new SolrQuery("text:\"The SD-500 product\"")).getResults().getNumFound());
  }
  @Test
  @Ignore // Stem Possessive is a feature of the WDF.
  public void testFulltextSearchEnglishPossessive() throws Exception {
    SolrServer solr = getSolr();
    SolrInputDocument doc = new SolrInputDocument();
    doc.addField("id", "1");
    doc.addField("text", "word Staffan's & Thomas' code");
    solr.add(doc);
    solr.commit();

    assertEquals(
        "Should match simple word",
        1,
        solr.query(new SolrQuery("text:word")).getResults().getNumFound());
    assertEquals(
        "Should match name 1",
        1,
        solr.query(new SolrQuery("text:staffan")).getResults().getNumFound());
    assertEquals(
        "Should match name 2",
        1,
        solr.query(new SolrQuery("text:thomas")).getResults().getNumFound());

    // Likely only possible with WDF in both pipelines or without WDF.
    /*
    assertEquals("Should match possessive name 1", 1, solr.query(new SolrQuery("text:Staffan's")).getResults().getNumFound());
    assertEquals("Should match possessive name 2", 1, solr.query(new SolrQuery("text:Thomas'")).getResults().getNumFound());
    */

    // Works when WDF is only in index pipeline.
    assertEquals(
        "Could match quoted no possessive",
        1,
        solr.query(new SolrQuery("text:\"Staffan & Thomas code\"")).getResults().getNumFound());

    // Likely only possible with WDF in query pipeline or without WDF.
    /*
    assertEquals("Could match quoted exact", 1, solr.query(new SolrQuery("text:\"Staffan's & Thomas' code\"")).getResults().getNumFound());
    */
  }
Exemplo n.º 26
0
  @RequestMapping("/search")
  public String search(ModelMap model) throws SolrServerException {
    SolrQuery query = new SolrQuery();

    /** 设置多条filterQuery语句有助于提高内存效率;组合查询条件设置单条filterQuery语句损耗内存多,但可以优化性能 可以采用 AND 或 OR 关键字 来设置查询与或 */
    query.setQuery("title:北京  OR content:北京");

    query.setRows(20);

    // 设置高亮
    query.setHighlight(true); // 开启高亮组件
    query.addHighlightField("title"); // 高亮字段
    query.addHighlightField("content"); // 高亮字段
    query.setHighlightSimplePre("<font color='red'>"); // 标记,高亮关键字前缀
    query.setHighlightSimplePost("</font>"); // 后缀
    query
        .setHighlight(true)
        .setHighlightSnippets(
            1); // 获取高亮分片数,一般搜索词可能分布在文章中的不同位置,其所在一定长度的语句即为一个片段,默认为1,但根据业务需要有时候需要多取出几个分片。 -
                // 此处设置决定下文中titleList, contentList中元素的个数
    query.setHighlightFragsize(150); // 每个分片的最大长度,默认为100。适当设置此值,如果太小,高亮的标题可能会显不全;设置太大,摘要可能会太长。

    QueryResponse response = solrServer.query(query);
    SolrDocumentList docs = response.getResults();

    // 获取所有高亮的字段
    Map<String, Map<String, List<String>>> highlightMap = response.getHighlighting();

    List<Article> articles = new ArrayList<Article>();
    for (SolrDocument solrDocument : docs) {
      Article article = new Article();

      List<String> titleList = highlightMap.get(solrDocument.getFieldValue("id")).get("title");
      List<String> contentList = highlightMap.get(solrDocument.getFieldValue("id")).get("content");

      // 获取并设置高亮的字段title
      if (titleList != null && titleList.size() > 0) {
        article.setTitle(titleList.get(0));
      }

      // 获取并设置高亮的字段content
      if (contentList != null && contentList.size() > 0) {
        article.setContent(contentList.get(0));
      }

      articles.add(article);
    }

    model.addAttribute("articles", articles);

    return "/client/article/list";
  }
Exemplo n.º 27
0
 protected void assertSolrQuery(Object result, String fld, String query) throws Exception {
   // check the field value of a result returned in the usual Solr way
   SolrQuery q = new SolrQuery(query);
   QueryResponse rsp = solr.query(q, METHOD.POST);
   NamedList<Object> response = rsp.getResponse();
   SolrDocumentList docs = (SolrDocumentList) response.get("response");
   if (result == null) {
     assertEquals(0, docs.size());
   } else {
     assertNotNull("no docs returned", docs);
     assertEquals("unexpected result count", 1, docs.size());
     assertEquals(result, docs.get(0).get(fld));
   }
 }
Exemplo n.º 28
0
  protected void execute() throws Exception {

    SolrServer server = new HttpSolrServer("http://localhost:8983/solr");
    SolrQuery query = new SolrQuery("text:ipod");
    QueryResponse response = server.query(query);

    SolrDocumentList docList = response.getResults();
    System.out.println("件数:" + docList.size());
    for (SolrDocument doc : docList) {
      System.out.println("■");
      for (String fieldName : doc.getFieldNames()) {
        System.out.println(fieldName.toString() + ":" + doc.getFieldValue(fieldName.toString()));
      }
    }
  }
Exemplo n.º 29
0
  public String getDocText(String id) throws SolrServerException {
    String q = "id:" + id;
    SolrQuery query = new SolrQuery();
    query.setQuery(q);
    query.setFields("text");
    QueryResponse rsp = server.query(query);

    String docText = "";
    if (rsp.getResults().getNumFound() > 0) {
      @SuppressWarnings({"unchecked", "rawtypes"})
      ArrayList<String> results = (ArrayList) rsp.getResults().get(0).getFieldValues("text");
      docText = results.get(0);
    }
    return docText;
  }
  @Test
  public void testFilenameNumberedDelimiterUnderscore() throws Exception {
    SolrServer solr = getSolr();
    SolrInputDocument doc1 = new SolrInputDocument();
    doc1.addField("id", "1");
    doc1.addField("pathnamebase", "MAP_12345678");
    solr.add(doc1);
    SolrInputDocument doc2 = new SolrInputDocument();
    doc2.addField("id", "2");
    doc2.addField("pathnamebase", "TOP_12345678");
    solr.add(doc2);
    solr.commit();

    assertEquals(
        "exact match",
        1,
        solr.query(new SolrQuery("name:MAP_12345678")).getResults().getNumFound());
    assertEquals(
        "exact match",
        1,
        solr.query(new SolrQuery("name:TOP_12345678")).getResults().getNumFound());

    assertEquals(
        "split on underscore", 1, solr.query(new SolrQuery("name:TOP")).getResults().getNumFound());
    assertEquals(
        "split on underscore",
        2,
        solr.query(new SolrQuery("name:12345678")).getResults().getNumFound());

    // no split on underscore - debatable but good when using numbering (have the option to use
    // space if splitting is desired)
    /*
    assertEquals("no split on underscore", 0, solr.query(new SolrQuery("name:TOP")).getResults().getNumFound());
    assertEquals("no split on underscore", 0, solr.query(new SolrQuery("name:12345678")).getResults().getNumFound());
    */
  }