当前位置: 首页>>代码示例>>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;未经允许,请勿转载。