com.erudika.para.server.search.es.ES Maven / Gradle / Ivy
Show all versions of para-search-elasticsearch Show documentation
/*
* Copyright 2013-2022 Erudika. http://erudika.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For issues and patches go to: https://github.com/erudika
*/
package com.erudika.para.server.search.es;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.SearchType;
import co.elastic.clients.elasticsearch._types.SortOptions;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.ChildScoreMode;
import co.elastic.clients.elasticsearch._types.query_dsl.Like;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders;
import co.elastic.clients.elasticsearch._types.query_dsl.QueryVariant;
import co.elastic.clients.elasticsearch.core.GetResponse;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.TotalHits;
import co.elastic.clients.elasticsearch.core.search.TotalHitsRelation;
import com.erudika.para.core.Address;
import com.erudika.para.core.App;
import com.erudika.para.core.ParaObject;
import com.erudika.para.core.Tag;
import com.erudika.para.core.persistence.DAO;
import com.erudika.para.core.utils.Config;
import com.erudika.para.core.utils.Pager;
import com.erudika.para.core.utils.Para;
import com.erudika.para.core.utils.Utils;
import static com.erudika.para.server.search.es.ESUtils.PROPS_PREFIX;
import static com.erudika.para.server.search.es.ESUtils.convertQueryStringToNestedQuery;
import static com.erudika.para.server.search.es.ESUtils.executeRequests;
import static com.erudika.para.server.search.es.ESUtils.getIndexName;
import static com.erudika.para.server.search.es.ESUtils.getNestedKey;
import static com.erudika.para.server.search.es.ESUtils.getPager;
import static com.erudika.para.server.search.es.ESUtils.getRESTClient;
import static com.erudika.para.server.search.es.ESUtils.getTermsQuery;
import static com.erudika.para.server.search.es.ESUtils.getValueFieldName;
import static com.erudika.para.server.search.es.ESUtils.keyValueBoolQuery;
import static com.erudika.para.server.search.es.ESUtils.nestedMode;
import static com.erudika.para.server.search.es.ESUtils.nestedPropsQuery;
import static com.erudika.para.server.search.es.ESUtils.qs;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Alex Bogdanovski [[email protected]]
*/
public final class ES {
private static final Logger logger = LoggerFactory.getLogger(ES.class);
private static DAO dao;
/**
* No-args constructor.
*/
private ES() { }
/**
* @param dao sets the DAO
*/
public static void setDao(DAO dao) {
ES.dao = dao;
}
public static void indexAllInternal(String appid, List
objects) {
if (StringUtils.isBlank(appid) || objects == null || objects.isEmpty()) {
return;
}
try {
executeRequests(objects.stream().
filter(Objects::nonNull).
map(obj -> BulkOperation.of(b -> b.update(d -> d.index(getIndexName(appid)).id(obj.getId()).
action(a -> a.doc(ESUtils.getSourceFromParaObject(obj)).docAsUpsert(true))))).
collect(Collectors.toList()));
logger.debug("Search.indexAll() {}", objects.size());
} catch (Exception e) {
logger.warn(null, e);
}
}
public static
void unindexAllInternal(String appid, List
objects) {
if (StringUtils.isBlank(appid) || objects == null || objects.isEmpty()) {
return;
}
try {
executeRequests(objects.stream().
filter(Objects::nonNull).
map(obj -> BulkOperation.of(b -> b.delete(d -> d.index(getIndexName(appid)).id(obj.getId())))).
collect(Collectors.toList()));
logger.debug("Search.unindexAll() {}", objects.size());
} catch (Exception e) {
logger.warn(null, e);
}
}
public static void unindexAllInternal(String appid, Map terms, boolean matchAll) {
if (StringUtils.isBlank(appid)) {
return;
}
try {
long time = System.nanoTime();
long unindexedCount = ESUtils.deleteByQuery(appid,
(terms == null || terms.isEmpty()) ? QueryBuilders.matchAll().build() : getTermsQuery(terms, matchAll));
time = System.nanoTime() - time;
logger.info("Unindexed {} documents without failures, took {}s.",
unindexedCount, TimeUnit.NANOSECONDS.toSeconds(time));
} catch (Exception e) {
logger.warn(null, e);
}
}
public static P findByIdInternal(String appid, String id) {
try {
return ESUtils.getParaObjectFromSource(getSource(appid, id));
} catch (Exception e) {
logger.warn(null, e);
return null;
}
}
@SuppressWarnings("unchecked")
public static
List
findByIdsInternal(String appid, List ids) {
List list = new LinkedList
();
if (ids == null || ids.isEmpty()) {
return list;
}
try {
List values = ids.stream().filter(Objects::nonNull).
map(v -> FieldValue.of(fv -> fv.stringValue(v))).collect(Collectors.toList());
QueryVariant qb = QueryBuilders.terms().field(Config._ID).terms(t -> t.value(values)).build();
return searchQuery(appid, null, qb);
} catch (Exception e) {
logger.warn(null, e);
}
return list;
}
public static List
findTermInListInternal(String appid, String type,
String field, List> terms, Pager... pager) {
if (StringUtils.isBlank(field) || terms == null) {
return Collections.emptyList();
}
QueryVariant qb;
if (nestedMode() && field.startsWith(PROPS_PREFIX)) {
QueryVariant bfb = null;
BoolQuery.Builder fb = QueryBuilders.bool();
for (Object term : terms) {
bfb = keyValueBoolQuery(field, String.valueOf(term));
fb.should(bfb._toQuery());
}
qb = (QueryVariant) nestedPropsQuery(terms.size() > 1 ? fb.build() : bfb).build();
} else {
List values = terms.stream().filter(Objects::nonNull).
map(v -> FieldValue.of(fv -> fv.stringValue(v.toString()))).collect(Collectors.toList());
qb = QueryBuilders.terms().field(field).terms(t -> t.value(values)).build();
}
return searchQuery(appid, type, qb, pager);
}
public static List
findPrefixInternal(String appid, String type,
String field, String prefix, Pager... pager) {
if (StringUtils.isBlank(field) || StringUtils.isBlank(prefix)) {
return Collections.emptyList();
}
QueryVariant qb;
if (nestedMode() && field.startsWith(PROPS_PREFIX)) {
qb = (QueryVariant) nestedPropsQuery(keyValueBoolQuery(field, QueryBuilders.prefix().
field(getValueFieldName(prefix)).value(prefix).build())).build();
} else {
qb = QueryBuilders.prefix().field(field).value(prefix).build();
}
return searchQuery(appid, type, qb, pager);
}
public static
List
findQueryInternal(String appid, String type,
String query, Pager... pager) {
if (StringUtils.isBlank(query)) {
return Collections.emptyList();
}
// a basic implementation of support for nested queries in query string
// https://github.com/elastic/elasticsearch/issues/11322
QueryVariant qb;
if (nestedMode()) {
qb = convertQueryStringToNestedQuery(query);
if (qb == null) {
return Collections.emptyList();
}
} else {
String qs = qs(query);
if ("*".equals(qs)) {
qb = QueryBuilders.matchAll().build();
} else {
qb = QueryBuilders.queryString().query(qs).allowLeadingWildcard(false).build();
}
}
return searchQuery(appid, type, qb, pager);
}
public static
List
findNestedQueryInternal(String appid, String type, String field,
String query, Pager... pager) {
if (StringUtils.isBlank(query) || StringUtils.isBlank(field)) {
return Collections.emptyList();
}
String queryString = "nstd." + field + ":" + query;
QueryVariant qb = QueryBuilders.nested().path("nstd").query(QueryBuilders.queryString().
query(qs(queryString)).build()._toQuery()).scoreMode(ChildScoreMode.Avg).build();
return searchQuery(appid, type, qb, pager);
}
public static
List
findWildcardInternal(String appid, String type,
String field, String wildcard, Pager... pager) {
if (StringUtils.isBlank(field) || StringUtils.isBlank(wildcard)) {
return Collections.emptyList();
}
QueryVariant qb;
if (nestedMode() && field.startsWith(PROPS_PREFIX)) {
qb = (QueryVariant) nestedPropsQuery(keyValueBoolQuery(field, QueryBuilders.
wildcard().field(getValueFieldName(wildcard)).value(wildcard).build())).build();
} else {
qb = QueryBuilders.wildcard().field(field).value(wildcard).build();
}
return searchQuery(appid, type, qb, pager);
}
public static
List
findTaggedInternal(String appid, String type,
String[] tags, Pager... pager) {
if (tags == null || tags.length == 0 || StringUtils.isBlank(appid)) {
return Collections.emptyList();
}
BoolQuery.Builder tagFilter = QueryBuilders.bool();
//assuming clean & safe tags here
for (String tag : tags) {
tagFilter.must(QueryBuilders.term().field(Config._TAGS).value(v -> v.stringValue(tag)).build()._toQuery());
}
// The filter looks like this: ("tag1" OR "tag2" OR "tag3") AND "type"
return searchQuery(appid, type, tagFilter.build(), pager);
}
@SuppressWarnings("unchecked")
public static
List
findTermsInternal(String appid, String type,
Map terms, boolean mustMatchAll, Pager... pager) {
if (terms == null || terms.isEmpty()) {
return Collections.emptyList();
}
QueryVariant fb = getTermsQuery(terms, mustMatchAll);
if (fb == null) {
return Collections.emptyList();
} else {
return searchQuery(appid, type, fb, pager);
}
}
public static List
findSimilarInternal(String appid, String type, String filterKey,
String[] fields, String liketext, Pager... pager) {
if (StringUtils.isBlank(liketext)) {
return Collections.emptyList();
}
QueryVariant qb;
String matchPercent = "70%";
if (fields == null || fields.length == 0) {
qb = QueryBuilders.moreLikeThis().like(l -> l.text(liketext)).
minDocFreq(1).minTermFreq(1).minimumShouldMatch(matchPercent).build();
} else {
boolean containsNestedProps = Arrays.stream(fields).anyMatch((f) -> StringUtils.startsWith(f, PROPS_PREFIX));
if (nestedMode() && containsNestedProps) {
BoolQuery.Builder bqb = QueryBuilders.bool();
for (String field : fields) {
QueryVariant kQuery = QueryBuilders.match().field(PROPS_PREFIX + "k").
query(v -> v.stringValue(getNestedKey(field))).build();
QueryVariant vQuery = QueryBuilders.moreLikeThis().fields(PROPS_PREFIX + "v").
like(Like.of(l -> l.text(liketext))).minDocFreq(1).minTermFreq(1).
minimumShouldMatch(matchPercent).build();
QueryVariant nested = (QueryVariant) nestedPropsQuery(QueryBuilders.bool().
must(kQuery._toQuery(), vQuery._toQuery()).build()).build();
bqb.should(nested._toQuery());
}
qb = bqb.build();
} else {
qb = QueryBuilders.moreLikeThis().fields(Arrays.asList(fields)).
like(l -> l.text(liketext)).minDocFreq(1).minTermFreq(1).minimumShouldMatch(matchPercent).build();
}
}
if (!StringUtils.isBlank(filterKey)) {
qb = QueryBuilders.bool().mustNot(QueryBuilders.term().field(Config._ID).value(v -> v.stringValue(filterKey)).
build()._toQuery()).filter(qb._toQuery()).build();
}
return searchQuery(appid, searchQueryRaw(appid, type, qb, pager));
}
public static
List
findTagsInternal(String appid, String keyword, Pager... pager) {
if (StringUtils.isBlank(keyword)) {
return Collections.emptyList();
}
QueryVariant qb = QueryBuilders.wildcard().field("tag").value(keyword.concat("*")).build();
return searchQuery(appid, Utils.type(Tag.class), qb, pager);
}
public static
List
findNearbyInternal(String appid, String type,
String query, int radius, double lat, double lng, Pager... pager) {
if (StringUtils.isBlank(type) || StringUtils.isBlank(appid)) {
return Collections.emptyList();
}
if (StringUtils.isBlank(query)) {
query = "*";
}
// find nearby Address objects
Pager page = getPager(pager);
QueryVariant qb1 = QueryBuilders.geoDistance().field("latlng").location(l -> l.latlon(ll -> ll.lat(lat).lon(lng))).
distance(Integer.toString(radius) + " km").build();
SearchResponse