當前位置: 首頁>>代碼示例>>Java>>正文


Java SearchHit類代碼示例

本文整理匯總了Java中org.elasticsearch.search.SearchHit的典型用法代碼示例。如果您正苦於以下問題:Java SearchHit類的具體用法?Java SearchHit怎麽用?Java SearchHit使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


SearchHit類屬於org.elasticsearch.search包,在下文中一共展示了SearchHit類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: doubleNotTest

import org.elasticsearch.search.SearchHit; //導入依賴的package包/類
@Test
public void doubleNotTest() throws IOException, SqlParseException, SQLFeatureNotSupportedException {
	SearchHits response1 = query(String.format("SELECT * FROM %s/account WHERE not gender like 'm' and not gender like 'f'", TEST_INDEX));
	Assert.assertEquals(0, response1.getTotalHits());

	SearchHits response2 = query(String.format("SELECT * FROM %s/account WHERE not gender like 'm' and gender not like 'f'", TEST_INDEX));
	Assert.assertEquals(0, response2.getTotalHits());

	SearchHits response3 = query(String.format("SELECT * FROM %s/account WHERE gender not like 'm' and gender not like 'f'", TEST_INDEX));
	Assert.assertEquals(0, response3.getTotalHits());

	SearchHits response4 = query(String.format("SELECT * FROM %s/account WHERE gender like 'm' and not gender like 'f'", TEST_INDEX));
	// assert there are results and they all have gender 'm'
	Assert.assertNotEquals(0, response4.getTotalHits());
	for (SearchHit hit : response4.getHits()) {
		Assert.assertEquals("m", hit.getSource().get("gender").toString().toLowerCase());
	}

	SearchHits response5 = query(String.format("SELECT * FROM %s/account WHERE NOT (gender = 'm' OR gender = 'f')", TEST_INDEX));
	Assert.assertEquals(0, response5.getTotalHits());
}
 
開發者ID:mazhou,項目名稱:es-sql,代碼行數:22,代碼來源:QueryTest.java

示例2: dateSearchBraces

import org.elasticsearch.search.SearchHit; //導入依賴的package包/類
@Test
 public void dateSearchBraces() throws IOException, SqlParseException, SQLFeatureNotSupportedException, ParseException {
     DateTimeFormatter formatter = DateTimeFormat.forPattern(TS_DATE_FORMAT);
     DateTime dateToCompare = new DateTime(2015, 3, 15, 0, 0, 0);

     SearchHits response = query(String.format("SELECT odbc_time FROM %s/odbc WHERE odbc_time < {ts '2015-03-15 00:00:00.000'}", TEST_INDEX));
     SearchHit[] hits = response.getHits();
     for(SearchHit hit : hits) {
         Map<String, Object> source = hit.getSource();
String insertTimeStr = (String) source.get("odbc_time");
insertTimeStr = insertTimeStr.replace("{ts '", "").replace("'}", "");

         DateTime insertTime = formatter.parseDateTime(insertTimeStr);

         String errorMessage = String.format("insert_time must be smaller then 2015-03-15. found: %s", insertTime);
         Assert.assertTrue(errorMessage, insertTime.isBefore(dateToCompare));
     }
 }
 
開發者ID:mazhou,項目名稱:es-sql,代碼行數:19,代碼來源:QueryTest.java

示例3: getDocumentUsingScroll

import org.elasticsearch.search.SearchHit; //導入依賴的package包/類
/**
 * This method used to get the document using scroll concept
 */
@Override
public void getDocumentUsingScroll() {
    try {
        client = ESclient.getInstant();
        QueryBuilder qb = termQuery("name", "sundar");
        SearchResponse scrollResp = client.prepareSearch("school", "college")
                .addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC)
                .setScroll(new TimeValue(60000))
                .setQuery(qb)
                .setSize(100).get(); //max of 100 hits will be returned for each scroll, Scroll until no hits are returned
        do {
            for (SearchHit hit : scrollResp.getHits().getHits()) {
                //Handle the hit...
                hit.getField("name");
            }

            scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();
        } while (scrollResp.getHits().getHits().length != 0); // Zero hits mark the end of the scroll and the while loop.
    } catch (Exception ex) {
        log.info("Exception occurred while Scroll Document : " + ex);
    }
}
 
開發者ID:sundarcse1216,項目名稱:es-crud,代碼行數:26,代碼來源:SearchAPIExampleImpl.java

示例4: ElasticsearchGraphQueryIterable

import org.elasticsearch.search.SearchHit; //導入依賴的package包/類
public ElasticsearchGraphQueryIterable(
        ElasticsearchSearchQueryBase query,
        SearchResponse searchResponse,
        QueryParameters parameters,
        Iterable<T> iterable,
        boolean evaluateQueryString,
        boolean evaluateHasContainers,
        boolean evaluateSortContainers,
        long totalHits,
        long searchTimeInNanoSeconds,
        SearchHits hits
) {
    super(parameters, iterable, evaluateQueryString, evaluateHasContainers, evaluateSortContainers);
    this.totalHits = totalHits;
    this.searchTimeInNanoSeconds = searchTimeInNanoSeconds;
    if (hits != null) {
        for (SearchHit hit : hits.getHits()) {
            scores.put(ElasticsearchDocIdUtils.fromSearchHit(hit), (double) hit.getScore());
        }
    }
    this.aggregationResults = getAggregationResults(query, searchResponse);
}
 
開發者ID:mware-solutions,項目名稱:memory-graph,代碼行數:23,代碼來源:ElasticsearchGraphQueryIterable.java

示例5: deleteES

import org.elasticsearch.search.SearchHit; //導入依賴的package包/類
private static void deleteES(Client client) {
  BulkRequestBuilder bulkRequest = client.prepareBulk();
  SearchResponse response = client.prepareSearch(index).setTypes(type)
      .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
      .setQuery(QueryBuilders.matchAllQuery())
      .setFrom(0).setSize(20).setExplain(true).execute().actionGet();
  System.out.println("length: " + response.getHits().getHits().length);
  if (response.getHits().getHits().length != 0) {
    for (SearchHit hit : response.getHits()) {
      String id = hit.getId();
      System.out.println("id: " + id);
      bulkRequest.add(client.prepareDelete(index, type, id).request());
    }
    BulkResponse bulkResponse = bulkRequest.get();
    if (bulkResponse.hasFailures()) {
      for (BulkItemResponse item : bulkResponse.getItems()) {
        System.out.println(item.getFailureMessage());
      }
    } else {
      System.out.println("delete ok");
    }
  } else {
    System.out.println("delete ok");
  }
}
 
開發者ID:MoneZhao,項目名稱:elasticsearch,代碼行數:26,代碼來源:App.java

示例6: createKeyToResultsAndFillOptimizationStructure

import org.elasticsearch.search.SearchHit; //導入依賴的package包/類
private void createKeyToResultsAndFillOptimizationStructure(Map<String,Map<String, List<Object>>> optimizationTermsFilterStructure, TableInJoinRequestBuilder firstTableRequest) {
    List<SearchHit> firstTableHits = fetchAllHits(firstTableRequest);

    int resultIds = 1;
    for (SearchHit hit : firstTableHits) {
        HashMap<String, List<Map.Entry<Field, Field>>> comparisons = this.hashJoinComparisonStructure.getComparisons();
        for (Map.Entry<String, List<Map.Entry<Field, Field>>> comparison : comparisons.entrySet()) {
            String comparisonID = comparison.getKey();
            List<Map.Entry<Field, Field>> t1ToT2FieldsComparison = comparison.getValue();

            String key = getComparisonKey(t1ToT2FieldsComparison, hit, true, optimizationTermsFilterStructure.get(comparisonID));

            //int docid , id
            InternalSearchHit searchHit = new InternalSearchHit(resultIds, hit.id(), new Text(hit.getType()), hit.getFields());
            searchHit.sourceRef(hit.getSourceRef());

            onlyReturnedFields(searchHit.sourceAsMap(), firstTableRequest.getReturnedFields(),firstTableRequest.getOriginalSelect().isSelectAll());
            resultIds++;
            this.hashJoinComparisonStructure.insertIntoComparisonHash(comparisonID, key, searchHit);
        }
    }
}
 
開發者ID:mazhou,項目名稱:es-sql,代碼行數:23,代碼來源:HashJoinElasticExecutor.java

示例7: getTopFilmes

import org.elasticsearch.search.SearchHit; //導入依賴的package包/類
public List<Map<String, Object>> getTopFilmes() {

		List<Map<String, Object>> filmes = new ArrayList<Map<String, Object>>();
		// Seu código deve vir daqui para baixo

		FieldSortBuilder sort = new FieldSortBuilder("vote_average").order(SortOrder.DESC);

		SearchResponse response = client.prepareSearch(INDEX).setTypes(TYPE).addSort(sort).execute().actionGet();

		SearchHit[] results = response.getHits().getHits();
		
		for (SearchHit hit : results) {
			System.out.println("------------------------------");
			Map<String, Object> result = hit.getSourceAsMap();
			filmes.add(result);
			System.out.println(result);
		}
		
		return filmes;
	}
 
開發者ID:wilkerjmachado,項目名稱:MoviesSearchPos,代碼行數:21,代碼來源:Filmes.java

示例8: getComparisonKey

import org.elasticsearch.search.SearchHit; //導入依賴的package包/類
private String getComparisonKey(List<Map.Entry<Field, Field>> t1ToT2FieldsComparison, SearchHit hit, boolean firstTable, Map<String, List<Object>> optimizationTermsFilterStructure) {
    String key = "";
    Map<String, Object> sourceAsMap = hit.sourceAsMap();
    for (Map.Entry<Field, Field> t1ToT2 : t1ToT2FieldsComparison) {
        //todo: change to our function find if key contains '.'
        String name;
        if (firstTable) name = t1ToT2.getKey().getName();
        else name = t1ToT2.getValue().getName();

        Object data = deepSearchInMap(sourceAsMap, name);
        if (firstTable && useQueryTermsFilterOptimization) {
            updateOptimizationData(optimizationTermsFilterStructure, data, t1ToT2.getValue().getName());
        }
        if (data == null)
            key += "|null|";
        else
            key += "|" + data.toString() + "|";
    }
    return key;
}
 
開發者ID:mazhou,項目名稱:es-sql,代碼行數:21,代碼來源:HashJoinElasticExecutor.java

示例9: mapEntity

import org.elasticsearch.search.SearchHit; //導入依賴的package包/類
public <T> T mapEntity(String source , SearchHit hit , Class<T> clazz) {
	T t = mapEntity(source , clazz) ;
	
	Map<String, HighlightField> highlightFields = hit.getHighlightFields();
	HighlightField highlightNameField = highlightFields.get("title");
	HighlightField contentHightlightField = highlightFields.get("content");
	try {
		if(highlightNameField!=null&&highlightNameField.fragments()!=null){
			PropertyUtils.setProperty(t, "title" , highlightNameField.fragments()[0].string());
		}
		if(contentHightlightField!=null){
			PropertyUtils.setProperty(t, "content" , contentHightlightField.fragments()[0].string());
		}
		PropertyUtils.setProperty(t, "id" , hit.getId());
	} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
		e.printStackTrace();
	} 
	return t;
}
 
開發者ID:uckefu,項目名稱:uckefu,代碼行數:20,代碼來源:UKResultMapper.java

示例10: leftJoinWithAllFromSecondTable

import org.elasticsearch.search.SearchHit; //導入依賴的package包/類
private void leftJoinWithAllFromSecondTable(boolean useNestedLoops) throws SQLFeatureNotSupportedException, IOException, SqlParseException {
    String query = String.format("select c.name.firstname , d.* from %s/gotCharacters c " +
            "LEFT JOIN %s/gotHouses d on d.name = c.house " +
            "where d.sigil <> 'direwolf'"
            ,  TEST_INDEX, TEST_INDEX);
    if(useNestedLoops) query = query.replace("select","select /*! USE_NL*/ ");
    SearchHit[] hits = joinAndGetHits(query);
    Assert.assertEquals(4, hits.length);
    for (SearchHit hit : hits) {
        if(hit.getId().endsWith("0")){
            Assert.assertEquals(1,hit.sourceAsMap().size());
        }
        else {
            Assert.assertEquals(5,hit.sourceAsMap().size());
        }
    }

}
 
開發者ID:mazhou,項目名稱:es-sql,代碼行數:19,代碼來源:JoinTests.java

示例11: fromXContent

import org.elasticsearch.search.SearchHit; //導入依賴的package包/類
public static Option fromXContent(XContentParser parser) {
    Map<String, Object> values = PARSER.apply(parser, null);

    Text text = new Text((String) values.get(Suggestion.Entry.Option.TEXT.getPreferredName()));
    Float score = (Float) values.get(Suggestion.Entry.Option.SCORE.getPreferredName());
    @SuppressWarnings("unchecked")
    Map<String, Set<CharSequence>> contexts = (Map<String, Set<CharSequence>>) values
            .get(CompletionSuggestion.Entry.Option.CONTEXTS.getPreferredName());
    if (contexts == null) {
        contexts = Collections.emptyMap();
    }

    SearchHit hit = null;
    // the option either prints SCORE or inlines the search hit
    if (score == null) {
        hit = SearchHit.createFromMap(values);
        score = hit.getScore();
    }
    CompletionSuggestion.Entry.Option option = new CompletionSuggestion.Entry.Option(-1, text, score, contexts);
    option.setHit(hit);
    return option;
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:23,代碼來源:CompletionSuggestion.java

示例12: testGeoBoundingBoxQueryForClient

import org.elasticsearch.search.SearchHit; //導入依賴的package包/類
@Test
public void testGeoBoundingBoxQueryForClient() throws Exception {

    QueryBuilder queryBuilder =
            QueryBuilders.geoBoundingBoxQuery("location")
                    .setCorners(40.124125,113.493763,39.816239,117.237612);



   SearchResponse searchResponse = client.prepareSearch()
            .setIndices("attractions")
            .setTypes("restaurant")
           .setPostFilter(queryBuilder)
            .execute()
            .actionGet();

    SearchHit[] searchHits = searchResponse.getHits().getHits();
    for (SearchHit searchHit :  searchHits){
        System.out.println(searchHit.getSource());
    }
}
 
開發者ID:felayman,項目名稱:elasticsearch-full,代碼行數:22,代碼來源:GeoPointDemo.java

示例13: deleteAll

import org.elasticsearch.search.SearchHit; //導入依賴的package包/類
public void deleteAll() {
    Client client = getConnection().getClient();

    TimeValue keepAlive = TimeValue.timeValueMinutes(10);
    SearchResponse response = client.prepareSearch(getIndex())
            .setTypes(getType())
            .setPostFilter(QueryBuilders.matchAllQuery())
            .setSize(100)
            .setScroll(keepAlive)
            .setFetchSource(true)
            .setExplain(false)
            .execute()
            .actionGet();
    do {
       Arrays.stream(response.getHits().getHits())
                .map(SearchHit::getSource)
                .filter(Objects::nonNull)
                .map(this::mapToHttpSource)
                .map(HttpSource::getUrl)
                .forEach(this::delete);
        response = client.prepareSearchScroll(response.getScrollId())
                .setScroll(keepAlive)
                .execute()
                .actionGet();
    } while (response.getHits().getHits().length != 0);
}
 
開發者ID:tokenmill,項目名稱:crawling-framework,代碼行數:27,代碼來源:EsHttpSourceOperations.java

示例14: parseSearchResult

import org.elasticsearch.search.SearchHit; //導入依賴的package包/類
private void parseSearchResult (SearchHit[] hits, boolean isHighLigth, EsQueryDo esQueryObj, JSONObject resObj) {
    List<JSONObject> searchRes = new ArrayList<JSONObject>();
    for (int i = 0; i < hits.length; i++) {
        SearchHit hit = hits[i];
        //將文檔中的每一個對象轉換json串值
        JSONObject hitJson=new  JSONObject();
        hitJson.put("id",hit.getId());
        hitJson.put("score",hit.getScore());
        JSONObject json = JSON.parseObject(hit.getSourceAsString());
        //如果高亮設置為true
        if (isHighLigth) {
            if (!Check.NuNObject(esQueryObj.highLigthFields())) {
                for (String hlFieldName : esQueryObj.highLigthFields()) {
                    highLightResult(json, hit, hlFieldName);
                }
            }

        }
        hitJson.put("source",json);
        searchRes.add(hitJson);
    }
    resObj.put("result", searchRes);

}
 
開發者ID:AsuraTeam,項目名稱:asura,代碼行數:25,代碼來源:EsQuery.java

示例15: wrap

import org.elasticsearch.search.SearchHit; //導入依賴的package包/類
private Response wrap(SearchResponse response) {
    List<SearchFailure> failures;
    if (response.getShardFailures() == null) {
        failures = emptyList();
    } else {
        failures = new ArrayList<>(response.getShardFailures().length);
        for (ShardSearchFailure failure: response.getShardFailures()) {
            String nodeId = failure.shard() == null ? null : failure.shard().getNodeId();
            failures.add(new SearchFailure(failure.getCause(), failure.index(), failure.shardId(), nodeId));
        }
    }
    List<Hit> hits;
    if (response.getHits().getHits() == null || response.getHits().getHits().length == 0) {
        hits = emptyList();
    } else {
        hits = new ArrayList<>(response.getHits().getHits().length);
        for (SearchHit hit: response.getHits().getHits()) {
            hits.add(new ClientHit(hit));
        }
        hits = unmodifiableList(hits);
    }
    return new Response(response.isTimedOut(), failures, response.getHits().getTotalHits(),
            hits, response.getScrollId());
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:25,代碼來源:ClientScrollableHitSource.java


注:本文中的org.elasticsearch.search.SearchHit類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。