本文整理汇总了Java中org.elasticsearch.index.query.MatchQueryBuilder类的典型用法代码示例。如果您正苦于以下问题:Java MatchQueryBuilder类的具体用法?Java MatchQueryBuilder怎么用?Java MatchQueryBuilder使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
MatchQueryBuilder类属于org.elasticsearch.index.query包,在下文中一共展示了MatchQueryBuilder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: searchByUserName
import org.elasticsearch.index.query.MatchQueryBuilder; //导入依赖的package包/类
public List<Person> searchByUserName(String userName) throws Exception {
List<Person> result = new ArrayList<>();
MatchQueryBuilder query = QueryBuilders.matchQuery("userName", userName);
SearchRequestBuilder searchRequestBuilder = client.prepareSearch(ES_INDEX).setTypes(ES_DOCTYPE).setQuery(query);
SearchResponse response = searchRequestBuilder.execute().actionGet();
if (response != null) {
SearchHits hits = response.getHits();
if (hits != null && hits.getTotalHits() > 0) {
for (SearchHit hit : hits) {
String personJson = hit.getSourceAsString();
ObjectMapper objectMapper = new ObjectMapper();
try {
Person person = objectMapper.readValue(personJson, Person.class);
result.add(person);
} catch (Exception e) {
LOGGER.error("Error while deserializing Elasticsearch Person document");
throw e;
}
}
}
}
return result;
}
示例2: testDefaults
import org.elasticsearch.index.query.MatchQueryBuilder; //导入依赖的package包/类
public void testDefaults() throws ExecutionException, InterruptedException {
MatchQuery.Type type = randomBoolean() ? MatchQueryBuilder.DEFAULT_TYPE : MatchQuery.Type.BOOLEAN;
SearchResponse searchResponse = client().prepareSearch("test")
.setQuery(randomizeType(multiMatchQuery("marvel hero captain america", "full_name", "first_name", "last_name", "category")
.operator(Operator.OR))).get();
Set<String> topNIds = Sets.newHashSet("theone", "theother");
for (int i = 0; i < searchResponse.getHits().getHits().length; i++) {
topNIds.remove(searchResponse.getHits().getAt(i).getId());
// very likely that we hit a random doc that has the same score so orders are random since
// the doc id is the tie-breaker
}
assertThat(topNIds, empty());
assertThat(searchResponse.getHits().getHits()[0].getScore(), greaterThan(searchResponse.getHits().getHits()[1].getScore()));
searchResponse = client().prepareSearch("test")
.setQuery(randomizeType(multiMatchQuery("marvel hero captain america", "full_name", "first_name", "last_name", "category")
.operator(Operator.OR).useDisMax(false).type(type))).get();
assertFirstHit(searchResponse, anyOf(hasId("theone"), hasId("theother")));
assertThat(searchResponse.getHits().getHits()[0].getScore(), greaterThan(searchResponse.getHits().getHits()[1].getScore()));
searchResponse = client().prepareSearch("test")
.setQuery(randomizeType(multiMatchQuery("marvel hero", "full_name", "first_name", "last_name", "category")
.operator(Operator.OR).type(type))).get();
assertFirstHit(searchResponse, hasId("theother"));
searchResponse = client().prepareSearch("test")
.setQuery(randomizeType(multiMatchQuery("captain america", "full_name", "first_name", "last_name", "category")
.operator(Operator.AND).type(type))).get();
assertHitCount(searchResponse, 1L);
assertFirstHit(searchResponse, hasId("theone"));
searchResponse = client().prepareSearch("test")
.setQuery(randomizeType(multiMatchQuery("captain america", "full_name", "first_name", "last_name", "category")
.operator(Operator.AND).type(type))).get();
assertHitCount(searchResponse, 1L);
assertFirstHit(searchResponse, hasId("theone"));
}
示例3: testFailedSearchWithWrongQuery
import org.elasticsearch.index.query.MatchQueryBuilder; //导入依赖的package包/类
public void testFailedSearchWithWrongQuery() throws Exception {
prepareData();
NumShards test = getNumShards("test");
logger.info("Start Testing failed search with wrong query");
try {
SearchResponse searchResponse = client().search(
searchRequest("test").source(new SearchSourceBuilder().query(new MatchQueryBuilder("foo", "biz")))).actionGet();
assertThat(searchResponse.getTotalShards(), equalTo(test.numPrimaries));
assertThat(searchResponse.getSuccessfulShards(), equalTo(0));
assertThat(searchResponse.getFailedShards(), equalTo(test.numPrimaries));
fail("search should fail");
} catch (ElasticsearchException e) {
assertThat(e.unwrapCause(), instanceOf(SearchPhaseExecutionException.class));
// all is well
}
logger.info("Done Testing failed search");
}
示例4: testFailedMultiSearchWithWrongQuery
import org.elasticsearch.index.query.MatchQueryBuilder; //导入依赖的package包/类
public void testFailedMultiSearchWithWrongQuery() throws Exception {
prepareData();
logger.info("Start Testing failed multi search with a wrong query");
MultiSearchResponse response = client().prepareMultiSearch()
.add(client().prepareSearch("test").setQuery(new MatchQueryBuilder("foo", "biz")))
.add(client().prepareSearch("test").setQuery(QueryBuilders.termQuery("nid", 2)))
.add(client().prepareSearch("test").setQuery(QueryBuilders.matchAllQuery()))
.execute().actionGet();
assertThat(response.getResponses().length, equalTo(3));
assertThat(response.getResponses()[0].getFailureMessage(), notNullValue());
assertThat(response.getResponses()[1].getFailureMessage(), nullValue());
assertThat(response.getResponses()[1].getResponse().getHits().getHits().length, equalTo(1));
assertThat(response.getResponses()[2].getFailureMessage(), nullValue());
assertThat(response.getResponses()[2].getResponse().getHits().getHits().length, equalTo(10));
logger.info("Done Testing failed search");
}
示例5: buildQueryBuilder
import org.elasticsearch.index.query.MatchQueryBuilder; //导入依赖的package包/类
private QueryBuilder buildQueryBuilder(ElasticsearchSearchOption option) {
ElasticsearchSearchOption.Operator op = option.getOperator();
MultiMatchQueryBuilder query = multiMatchQuery(
option.getKeyword(),
option.getSearchFields().stream().toArray(String[]::new));
if (op != null && ElasticsearchSearchOption.Operator.AND == op) {
query = query.operator(MatchQueryBuilder.Operator.AND);
}
if (option.getOptionalSearchConditions().isEmpty()) {
return query;
} else {
BoolQueryBuilder q = boolQuery().must(query);
option.getOptionalSearchConditions().forEach((k, v) -> {
q.must(matchQuery(k, v));
});
return q;
}
}
示例6: testParseFeatureAsString
import org.elasticsearch.index.query.MatchQueryBuilder; //导入依赖的package包/类
public void testParseFeatureAsString() throws IOException {
String featureString = "{\n" +
"\"name\": \"testFeature\",\n" +
"\"params\": [\"param1\", \"param2\"],\n" +
"\"template_language\": \"mustache\",\n" +
"\"template\": \"" +
new MatchQueryBuilder("match_field", "match_word").toString(NOT_PRETTY)
.replace("\"", "\\\"") +
"\"\n}\n";
StoredFeature feature = parse(featureString);
assertEquals("testFeature", feature.name());
assertArrayEquals(Arrays.asList("param1", "param2").toArray(), feature.queryParams().toArray());
assertEquals("mustache", feature.templateLanguage());
assertEquals(new MatchQueryBuilder("match_field", "match_word").toString(NOT_PRETTY),
feature.template());
assertTrue(feature.templateAsString());
}
示例7: setUp
import org.elasticsearch.index.query.MatchQueryBuilder; //导入依赖的package包/类
@Before
public void setUp() throws Exception {
super.setUp();
store.clear();
StoredFeature feature1 = new StoredFeature("match1", Collections.singletonList("query_string"),
"mustache",
new MatchQueryBuilder("field1", "{{query_string}}").toString());
StoredFeature feature2 = new StoredFeature("match2", Collections.singletonList("query_string"),
"mustache",
new MatchQueryBuilder("field2", "{{query_string}}").toString());
StoredFeature feature3 = new StoredFeature("score3", Collections.emptyList(),
"mustache",
new FunctionScoreQueryBuilder(new FieldValueFactorFunctionBuilder("scorefield2")
.factor(1.2F)
.modifier(FieldValueFactorFunction.Modifier.LN2P)
.missing(0F)).toString());
StoredFeatureSet set = new StoredFeatureSet("set1", Arrays.asList(feature1, feature2, feature3));
store.add(set);
LtrRanker ranker = new LinearRanker(new float[]{0.1F, 0.2F, 0.3F});
CompiledLtrModel model = new CompiledLtrModel("model1", set, ranker);
store.add(model);
}
示例8: testQueryWithIndex
import org.elasticsearch.index.query.MatchQueryBuilder; //导入依赖的package包/类
@Test
public void testQueryWithIndex() throws Exception {
// Prepare: Setup Thrift Client and add some docs
client = pool.getClient(SERVICE_NAME, EzElastic.Client.class);
client.bulkPut(
Arrays.asList(washingtonMonumentDoc, whiteHouseDoc, oneaaColumbiaDoc, oneaaNavyYardDoc), fakeSecurity);
// Action: Create and execute an AND match query on title
final String elasticQuery =
QueryBuilders.matchQuery("title", "42Six HQ").operator(MatchQueryBuilder.Operator.AND).toString();
final SearchResult results = client.query(new Query(elasticQuery), fakeSecurity);
// Assert: There should be a single matching document due to the AND operator
assertEquals(1, results.getTotalHits());
assertEquals(oneaaColumbiaDoc.get_id(), results.getMatchingDocuments().get(0).get_id());
pool.returnToPool(client);
}
示例9: visit
import org.elasticsearch.index.query.MatchQueryBuilder; //导入依赖的package包/类
@Override
public void visit( ContainsOperand op ) throws NoFullTextIndexException {
final String name = op.getProperty().getValue().toLowerCase();
final String value = op.getLiteral().getValue().toString().toLowerCase();
// or field is just a string that does need a prefix
if ( value.indexOf( "*" ) != -1 ) {
final WildcardQueryBuilder wildcardQuery =
QueryBuilders.wildcardQuery( IndexingUtils.FIELD_STRING_NESTED, value );
queryBuilders.push( fieldNameTerm( name, wildcardQuery ) );
}
else {
final MatchQueryBuilder termQuery = QueryBuilders.matchQuery( IndexingUtils.FIELD_STRING_NESTED, value );
queryBuilders.push( fieldNameTerm( name, termQuery ) );
}
//no op for filters, push an empty operation
//TODO, validate this works
filterBuilders.push( NoOpFilterBuilder.INSTANCE );
}
示例10: testConcurrentDeleteByQueriesOnSameDocs
import org.elasticsearch.index.query.MatchQueryBuilder; //导入依赖的package包/类
public void testConcurrentDeleteByQueriesOnSameDocs() throws Throwable {
final long docs = randomIntBetween(50, 100);
List<IndexRequestBuilder> builders = new ArrayList<>();
for (int i = 0; i < docs; i++) {
builders.add(client().prepareIndex("test", "doc", String.valueOf(i)).setSource("foo", "bar"));
}
indexRandom(true, true, true, builders);
final Thread[] threads = new Thread[scaledRandomIntBetween(2, 9)];
final CountDownLatch start = new CountDownLatch(1);
final MatchQueryBuilder query = matchQuery("foo", "bar");
final AtomicLong deleted = new AtomicLong(0);
for (int t = 0; t < threads.length; t++) {
Runnable r = () -> {
try {
start.await();
BulkByScrollResponse response = deleteByQuery().source("test").filter(query).refresh(true).get();
// Some deletions might fail due to version conflict, but
// what matters here is the total of successful deletions
deleted.addAndGet(response.getDeleted());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
};
threads[t] = new Thread(r);
threads[t].start();
}
start.countDown();
for (Thread thread : threads) {
thread.join();
}
assertHitCount(client().prepareSearch("test").setSize(0).get(), 0L);
assertThat(deleted.get(), equalTo(docs));
}
示例11: testHighlightersIgnoreParentChild
import org.elasticsearch.index.query.MatchQueryBuilder; //导入依赖的package包/类
public void testHighlightersIgnoreParentChild() {
assertAcked(prepareCreate("test")
.addMapping("parent-type", "searchText", "type=text,term_vector=with_positions_offsets,index_options=offsets")
.addMapping("child-type", "_parent", "type=parent-type", "searchText",
"type=text,term_vector=with_positions_offsets,index_options=offsets"));
client().prepareIndex("test", "parent-type", "parent-id").setSource("searchText", "quick brown fox").get();
client().prepareIndex("test", "child-type", "child-id").setParent("parent-id").setSource("searchText", "quick brown fox").get();
refresh();
String[] highlightTypes = new String[] {"plain", "fvh", "postings"};
for (String highlightType : highlightTypes) {
logger.info("Testing with highlight type [{}]", highlightType);
SearchResponse searchResponse = client().prepareSearch("test")
.setQuery(new BoolQueryBuilder()
.must(new MatchQueryBuilder("searchText", "fox"))
.must(new HasChildQueryBuilder("child-type", new MatchAllQueryBuilder(), ScoreMode.None))
)
.highlighter(new HighlightBuilder().field(new HighlightBuilder.Field("searchText").highlighterType(highlightType)))
.get();
assertHitCount(searchResponse, 1);
assertThat(searchResponse.getHits().getAt(0).getId(), equalTo("parent-id"));
HighlightField highlightField = searchResponse.getHits().getAt(0).getHighlightFields().get("searchText");
assertThat(highlightField.getFragments()[0].string(), equalTo("quick brown <em>fox</em>"));
searchResponse = client().prepareSearch("test")
.setQuery(new BoolQueryBuilder()
.must(new MatchQueryBuilder("searchText", "fox"))
.must(new HasParentQueryBuilder("parent-type", new MatchAllQueryBuilder(), false))
)
.highlighter(new HighlightBuilder().field(new HighlightBuilder.Field("searchText").highlighterType(highlightType)))
.get();
assertHitCount(searchResponse, 1);
assertThat(searchResponse.getHits().getAt(0).getId(), equalTo("child-id"));
highlightField = searchResponse.getHits().getAt(0).getHighlightFields().get("searchText");
assertThat(highlightField.getFragments()[0].string(), equalTo("quick brown <em>fox</em>"));
}
}
示例12: createSemQuery
import org.elasticsearch.index.query.MatchQueryBuilder; //导入依赖的package包/类
/**
* Method of creating semantic query based on Threshold
*
* @param input regular query
* @param T threshold raning from 0 to 1
* @param query_operator query mode
* @return a multiMatch query builder
*/
public BoolQueryBuilder createSemQuery(String input, double T, String query_operator) {
Map<String, Double> selected_Map = getRelatedTermsByT(input, T);
selected_Map.put(input, (double) 1);
String fieldsList[] = { "Dataset-Metadata", "Dataset-ShortName", "Dataset-LongName",
"DatasetParameter-Topic", "DatasetParameter-VariableDetail", "DatasetParameter-Category",
"DatasetParameter-Variable", "DatasetParameter-Term",
"DatasetSource-Source-LongName", "DatasetSource-Source-LongName-Full",
"DatasetSource-Source-ShortName", "DatasetSource-Source-ShortName-Full",
"DatasetSource-Sensor-LongName", "DatasetSource-Sensor-LongName-Full", "DatasetSource-Sensor-ShortName",
"DatasetSource-Sensor-ShortName-Full" };
BoolQueryBuilder qb = new BoolQueryBuilder();
for (Entry<String, Double> entry : selected_Map.entrySet()) {
if (query_operator.toLowerCase().trim().equals("phrase")) {
qb.should(QueryBuilders.multiMatchQuery(entry.getKey(), fieldsList).boost(entry.getValue().floatValue()).type(MultiMatchQueryBuilder.Type.PHRASE).tieBreaker((float) 0.5)); // when
// set
// to
// 1.0,
// it
// would
// be
// equal
// to
// "most
// fields"
// query
} else if (query_operator.toLowerCase().trim().equals("and")) {
qb.should(QueryBuilders.multiMatchQuery(entry.getKey(), fieldsList).boost(entry.getValue().floatValue()).operator(MatchQueryBuilder.DEFAULT_OPERATOR.AND).tieBreaker((float) 0.5));
} else {
qb.should(QueryBuilders.multiMatchQuery(entry.getKey(), fieldsList).boost(entry.getValue().floatValue()).operator(MatchQueryBuilder.DEFAULT_OPERATOR.OR).tieBreaker((float) 0.5));
}
}
// LOG.info(qb.toString());
return qb;
}
示例13: createMatchQuery
import org.elasticsearch.index.query.MatchQueryBuilder; //导入依赖的package包/类
private static MatchQueryBuilder createMatchQuery(String name, Object text, Float boost) {
if (isNotNull(boost)) {
return QueryBuilders.matchQuery(name, text).boost(boost);
} else {
return QueryBuilders.matchQuery(name, text);
}
}
示例14: fullParamer
import org.elasticsearch.index.query.MatchQueryBuilder; //导入依赖的package包/类
public static ToXContent fullParamer(MatchQueryBuilder query, Paramer paramer) {
if (paramer.analysis != null) {
query.analyzer(paramer.analysis);
}
if (paramer.boost != null) {
query.boost(paramer.boost);
}
return query;
}
示例15: generateTestFeature
import org.elasticsearch.index.query.MatchQueryBuilder; //导入依赖的package包/类
public static String generateTestFeature(String name) {
return "{\n" +
"\"name\": \""+name+"\",\n" +
"\"params\": [\"param1\", \"param2\"],\n" +
"\"template_language\": \"mustache\",\n" +
"\"template\": \n" +
new MatchQueryBuilder("match_field", "match_word").toString() +
"\n}\n";
}