feature/city_search #156

Merged
jahn merged 5 commits from feature/city_search into master 2021-03-01 19:00:43 +01:00
11 changed files with 107 additions and 71 deletions
@@ -57,7 +57,7 @@ public class DrawerViewModel extends AbstractNetworkViewModel {
* The task to perform the search.
*/
private ApiTask<RequestParameter<String>, LocationHierarchyPage> searchTask = new ApiTask<>((input, client) -> {
return client.searchLocations(getLanguage(), input.getValue(), 0, 10, null);
return client.searchLocations(getLanguage(), input.getValue(), 0, 10, null, false);
}, (input, result) -> {
completeRequest(input, () -> {
results.setValue(result);
@@ -1,12 +1,14 @@
package com.mowesta.api.location;
import javax.annotation.security.PermitAll;
import javax.enterprise.inject.Default;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.ws.rs.BeanParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
@@ -56,7 +58,8 @@ public interface ILocationService {
})
@PermitAll
Response searchLocations(@BeanParam @Valid PageConfig pageConfig, @BeanParam @Valid SearchContext context,
@ApiParam(value="The search term.", required=true) @QueryParam("term") @NotNull @Valid String term);
@ApiParam(value="The search term.", required=true) @QueryParam("term") @NotNull @Valid String term,
@QueryParam("onlyCities") @ApiParam(value = "True if only cities are desired") @DefaultValue("false") boolean onlyCities);
@@ -54,7 +54,7 @@ public class AlexaIntentService {
if (city == null) {
location = getGeoLocation(input);
} else {
LocationHierarchyPage locationHierarchyPage = locationSessionBean.findLocations(new PageConfig(0, 60), new SearchContext(language), city);
LocationHierarchyPage locationHierarchyPage = locationSessionBean.findLocations(new PageConfig(0, 60), new SearchContext(language), city, false);
location = getLocation(intentRequest, locationHierarchyPage);
}
return location;
@@ -33,14 +33,14 @@ import com.mowesta.api.Language;
import com.mowesta.api.PageConfig;
/**
* The base class for locations such as cities, states and countries.
*
* The base class for locations such as cities, states and countries.
*
* @author Marcus
*/
@Entity
@SuppressWarnings("serial")
public abstract class AbstractLocationEntity extends AbstractSpatialEntity {
/**
* The maximum batch size to use when to load the result of a search.
*/
@@ -52,7 +52,7 @@ public abstract class AbstractLocationEntity extends AbstractSpatialEntity {
* nominatim installation.
*/
private long externalId;
/**
* The names of the location.
*/
@@ -60,7 +60,7 @@ public abstract class AbstractLocationEntity extends AbstractSpatialEntity {
@Embedded
@IndexedEmbedded
private EmbeddedName names;
/**
* The boundary of the location as a geojson string.
*/
@@ -73,35 +73,35 @@ public abstract class AbstractLocationEntity extends AbstractSpatialEntity {
@Field(name = "importance")
@SortableField
private double importance;
/**
* The nominatim search rank. The search rank describes the extent and importance of a place.
* It is used when ranking search result. Simply put, if there are two results for a search
* query which are otherwise equal, then the result with the lower search rank will be appear
* higher in the result list. Search ranks are not so important these days because many
* The nominatim search rank. The search rank describes the extent and importance of a place.
* It is used when ranking search result. Simply put, if there are two results for a search
* query which are otherwise equal, then the result with the lower search rank will be appear
* higher in the result list. Search ranks are not so important these days because many
* well-known places use the Wikipedia importance ranking instead.
*/
@Field(name = "searchRank")
@SortableField
private int searchRank;
/**
* The nominatim address rank. The address rank describes where a place shows up in an
* address hierarchy. Usually only administrative boundaries and place nodes and areas
* The nominatim address rank. The address rank describes where a place shows up in an
* address hierarchy. Usually only administrative boundaries and place nodes and areas
* are eligible to be part of an address. All other objects have an address rank of 0.
* Note that the search rank of a place plays a role in the address computation as well.
* When collecting the places that should make up the address parts then only places are
* Note that the search rank of a place plays a role in the address computation as well.
* When collecting the places that should make up the address parts then only places are
* taken into account that have a lower address rank than the search rank of the base object.
*/
@Field(name = "addressRank")
@SortableField
private int addressRank;
/**
* The optional wikipedia entry.
*/
private String wikipedia;
/**
* Returns the externalId.
*
@@ -119,7 +119,7 @@ public abstract class AbstractLocationEntity extends AbstractSpatialEntity {
public void setExternalId(long externalId) {
this.externalId = externalId;
}
/**
* Returns the names.
*
@@ -227,10 +227,10 @@ public abstract class AbstractLocationEntity extends AbstractSpatialEntity {
public void setWikipedia(String wikipedia) {
this.wikipedia = wikipedia;
}
/**
* Finds all entities of the specified type that have the specified external id.
*
*
* @param <E> The entity type.
* @param em The entity manager.
* @param type The entity type.
@@ -249,34 +249,38 @@ public abstract class AbstractLocationEntity extends AbstractSpatialEntity {
if (result.size() == 1) return result.get(0);
throw new RuntimeException("Found duplicate external id for location of type " + type.getClass().getName() + ".");
}
/**
* Returns an approximate number of results for a query for the term.
*
*
* @param em The entity manager.
* @param language The user interface language.
* @param term The search term.
* @param onlyCities True if only cities should be searched
* @return The count.
*/
public static int countAllByTerm(EntityManager em, Language language, String term) {
FullTextQuery query = createQueryByTerm(em, language, term);
public static int countAllByTerm(EntityManager em, Language language, String term, boolean onlyCities) {
FullTextQuery query = createQueryByTerm(em, language, term, onlyCities);
return query.getResultSize();
}
/**
* Returns the list of cities whose names matches the query for the specified
* page config.
*
*
* @param em The entity manager.
* @param config The page config to limit the result.
* @param language The user interface language.
* @param term The search term.
* @param onlyCities True if only cities should be searched.
* @return The result list.
*/
@SuppressWarnings("unchecked")
public static List<AbstractLocationEntity> findAllByTerm(EntityManager em, PageConfig config, Language language, String term) {
FullTextQuery query = createQueryByTerm(em, language, term);
public static List<AbstractLocationEntity> findAllByTerm(EntityManager em, PageConfig config,
Language language, String term,
boolean onlyCities) {
FullTextQuery query = createQueryByTerm(em, language, term, onlyCities);
query.setSort(new Sort(SortField.FIELD_SCORE, new SortField("importance", Type.DOUBLE, true), new SortField("searchRank", Type.INT)));
query.setFirstResult(config.getOffset());
query.setMaxResults(config.getSize());
@@ -289,25 +293,36 @@ public abstract class AbstractLocationEntity extends AbstractSpatialEntity {
/**
* Creates a full-text query over the cities that searches in the city, country
* and state names.
*
*
* @param em The entity manager.
* @param language The ui language.
* @param term The term to search.
* @param onlyCities True if only cities should be considered
* @return The query.
*/
private static FullTextQuery createQueryByTerm(EntityManager em, Language language, String term) {
private static FullTextQuery createQueryByTerm(EntityManager em, Language language, String term,
boolean onlyCities) {
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);
QueryBuilder baseBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(AbstractLocationEntity.class).get();
Query q1 = createSubQuery(fullTextEntityManager, CityEntity.class, new String[] { "names", "state.names", "country.names" }, language, term);
Query q2 = createSubQuery(fullTextEntityManager, StateEntity.class, new String[] { "names", "country.names" }, language, term);
Query q3 = createSubQuery(fullTextEntityManager, CountryEntity.class, new String[] { "names" }, language, term);
Query query = baseBuilder.bool().should(q1).should(q2).should(q3).createQuery();
return fullTextEntityManager.createFullTextQuery(query, AbstractLocationEntity.class);
Query query;
if (onlyCities) {
Query q1 = createSubQuery(fullTextEntityManager, CityEntity.class, new String[]{"names"}, language, term);
query = baseBuilder.bool().should(q1).createQuery();
} else {
Query q1 = createSubQuery(fullTextEntityManager, CityEntity.class, new String[]{"names", "state.names", "country.names"}, language, term);
Query q2 = createSubQuery(fullTextEntityManager, StateEntity.class, new String[]{"names", "country.names"}, language, term);
Query q3 = createSubQuery(fullTextEntityManager, CountryEntity.class, new String[]{"names"}, language, term);
query = baseBuilder.bool().should(q1).should(q2).should(q3).createQuery();
}
if (onlyCities)
return fullTextEntityManager.createFullTextQuery(query, CityEntity.class);
else return fullTextEntityManager.createFullTextQuery(query, AbstractLocationEntity.class);
}
/**
* Creates a sub query for a particular entity type.
*
*
* @param tem The full text entity manager.
* @param cls The type to search for.
* @param text The location of text fields.
@@ -352,10 +367,10 @@ public abstract class AbstractLocationEntity extends AbstractSpatialEntity {
QueryBuilder builder = context.get();
return builder.keyword().onFields(fields).matching(term).createQuery();
}
/**
* Loads all location entites from a projection represented as an array consisting of (at least) object class and object id.
*
*
* @param <T> The return type.
* @param em The entity manager.
* @param projection The project.
@@ -390,15 +405,15 @@ public abstract class AbstractLocationEntity extends AbstractSpatialEntity {
T e = entitiesById.get(id);
if (e != null) {
result.add(e);
}
}
}
return result;
}
/**
* Returns an approximate number of results for a range query.
*
*
* @param em The entity manager.
* @param c1 The first coordinate.
* @param c2 The second coordinate.
@@ -410,12 +425,12 @@ public abstract class AbstractLocationEntity extends AbstractSpatialEntity {
return query.getResultSize();
}
/**
* Performs a search within a range defined by two coordinates.
*
*
*
*
* @param <T> The type of object to search.
* @param em The entity manager.
* @param config The page configuration.
@@ -426,7 +441,7 @@ public abstract class AbstractLocationEntity extends AbstractSpatialEntity {
*/
@SuppressWarnings("unchecked")
public static <T extends AbstractLocationEntity> List<T> findAllByRange(EntityManager em, PageConfig config, Coordinate c1, Coordinate c2, Class<T> type) {
FullTextQuery query = createRangeQuery(em, c1, c2, type);
FullTextQuery query = createRangeQuery(em, c1, c2, type);
query.setSort(new Sort(SortField.FIELD_SCORE, new SortField("importance", Type.DOUBLE, true), new SortField("addressRank", Type.INT)));
query.setFirstResult(config.getOffset());
query.setMaxResults(config.getSize());
@@ -434,10 +449,10 @@ public abstract class AbstractLocationEntity extends AbstractSpatialEntity {
List<Object[]> projection = (List<Object[]>) query.getResultList();
return loadAll(em, projection, type);
}
/**
* Creates a range query over a location.
*
*
* @param em The entity manager.
* @param c1 The first coordinate.
* @param c2 The second coordinate.
@@ -454,7 +469,7 @@ public abstract class AbstractLocationEntity extends AbstractSpatialEntity {
Query query = builder.bool().must(minLat).must(maxLat).must(minLon).must(maxLon).createQuery();
return fullTextEntityManager.createFullTextQuery(query, type);
}
}
@@ -54,15 +54,16 @@ public class LocationSessionBean extends AbstractSessionBean {
* @return The page with the results.
*/
@PermitAll
public LocationHierarchyPage findLocations(PageConfig config, SearchContext context, String term) {
public LocationHierarchyPage findLocations(PageConfig config, SearchContext context, String term,
boolean onlyCities) {
LocationHierarchyPage page = new LocationHierarchyPage();
page.setOffset(config.getOffset());
page.setSize(config.getSize());
if (term != null && term.length() > 1) {
log.log(Level.INFO, "Counting locations for search term: " + term);
page.setTotal(AbstractLocationEntity.countAllByTerm(em, context.getLanguage(), term));
page.setTotal(AbstractLocationEntity.countAllByTerm(em, context.getLanguage(), term, onlyCities));
log.log(Level.INFO, "Computing result set for search term: " + term);
List<AbstractLocationEntity> locations = AbstractLocationEntity.findAllByTerm(em, config, context.getLanguage(), term);
List<AbstractLocationEntity> locations = AbstractLocationEntity.findAllByTerm(em, config, context.getLanguage(), term, onlyCities);
log.log(Level.INFO, "Converting result set for search term: " + term);
page.setElements(Convert.with(LocationHierarchyConverter.class)
.apply(locations, false));
@@ -416,11 +416,11 @@ public class LocationSyncSessionBean extends AbstractSyncSessionBean {
protected boolean isIndexHealthy() {
PageConfig config = new PageConfig(0, 1);
SearchContext context = new SearchContext(Language.GERMAN);
if (AbstractLocationEntity.findAllByTerm(em, config, context.getLanguage(), "Deutschland").size() == 0) return false;
if (AbstractLocationEntity.findAllByTerm(em, config, context.getLanguage(), "Essen").size() == 0) return false;
if (AbstractLocationEntity.findAllByTerm(em, config, context.getLanguage(), "Deutschland", false).size() == 0) return false;
if (AbstractLocationEntity.findAllByTerm(em, config, context.getLanguage(), "Essen", false).size() == 0) return false;
context = new SearchContext(Language.ENGLISH);
if (AbstractLocationEntity.findAllByTerm(em, config, context.getLanguage(), "Germany").size() == 0) return false;
if (AbstractLocationEntity.findAllByTerm(em, config, context.getLanguage(), "Essen").size() == 0) return false;
if (AbstractLocationEntity.findAllByTerm(em, config, context.getLanguage(), "Germany", false).size() == 0) return false;
if (AbstractLocationEntity.findAllByTerm(em, config, context.getLanguage(), "Essen", false).size() == 0) return false;
return true;
}
@@ -160,6 +160,22 @@ public class LocationSessionTest extends AbstractSessionTest {
germanyPage.getElements().get(0).getNames().get(Language.LOCAL).equals("Berlin");
}
/**
* Tests if it is possible to only get cities as results.
*/
@Test
public void testCities() {
LocationHierarchyPage berlinPage = locationSession.findLocations(new PageConfig(0, 20), new SearchContext(Language.GERMAN), "Berlin", true);
Assert.assertEquals(2, berlinPage.getElements().size());
berlinPage.getElements().forEach(locationHierarchy -> Assert.assertEquals(LocationType.CITY, locationHierarchy.getType()));
LocationHierarchyPage nrwPage = locationSession.findLocations(new PageConfig(0, 20), new SearchContext(Language.GERMAN), "Nordrhein-Westfahlen", true);
Assert.assertEquals(0, nrwPage.getElements().size());
LocationHierarchyPage bwPage = locationSession.findLocations(new PageConfig(0, 20), new SearchContext(Language.GERMAN), "Baden-Württemberg", true);
Assert.assertEquals(0, bwPage.getElements().size());
}
/**
* Checks that the search for the term has the specified number of
* results from the specified type. The other types are ignored.
@@ -171,7 +187,7 @@ public class LocationSessionTest extends AbstractSessionTest {
* @return The result page.
*/
private LocationHierarchyPage assertSearchResultCount(LocationType type, int results, Language language, String term) {
LocationHierarchyPage page = locationSession.findLocations(new PageConfig(0, 20), new SearchContext(language), term);
LocationHierarchyPage page = locationSession.findLocations(new PageConfig(0, 20), new SearchContext(language), term, false);
int actual = 0;
for (LocationHierarchy location: page.getElements()) {
if (location.getType() == type) actual += 1;
@@ -53,7 +53,7 @@ public class SettingsSessionTest extends AbstractSessionTest {
public void run() {
try {
Settings settings = settingsSession.getCurrentUserSettings();
LocationHierarchyPage page = locationSession.findLocations(new PageConfig(0, 1), new SearchContext(Language.GERMAN), "Bonn");
LocationHierarchyPage page = locationSession.findLocations(new PageConfig(0, 1), new SearchContext(Language.GERMAN), "Bonn", false);
LocationHierarchy bonn = page.getElements().get(0);
Assert.assertEquals("Search result should have one entry.", 1, page.getSize());
Assert.assertEquals("Search result should be type city.", LocationType.CITY, bonn.getType());
@@ -96,7 +96,7 @@ public class SettingsSessionTest extends AbstractSessionTest {
public void run() {
try {
Settings settings = settingsSession.getCurrentUserSettings();
LocationHierarchyPage page = locationSession.findLocations(new PageConfig(0, 1), new SearchContext(Language.GERMAN), "Bonn");
LocationHierarchyPage page = locationSession.findLocations(new PageConfig(0, 1), new SearchContext(Language.GERMAN), "Bonn", false);
LocationHierarchy bonn = page.getElements().get(0);
LocationHierarchy nrw = bonn.getParent();
LocationHierarchy germany = nrw.getParent();
@@ -7,6 +7,7 @@ import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.EntityTag;
import javax.ws.rs.core.Request;
@@ -56,11 +57,11 @@ public class LocationResource implements ILocationService {
@Override
public Response searchLocations(PageConfig pageConfig, SearchContext context, String term) {
public Response searchLocations(PageConfig pageConfig, SearchContext context, String term, boolean onlyCities) {
EntityTag tag = new EntityTag(Long.toString(locationSession.getLastModifiedLocation()));
ResponseBuilder b = request.evaluatePreconditions(tag);
if (b == null) {
b = Response.ok(locationSession.findLocations(pageConfig, context, term));
b = Response.ok(locationSession.findLocations(pageConfig, context, term, onlyCities));
}
return b.tag(tag).build();
}
@@ -53,7 +53,7 @@ public class LocationResourceTest extends AbstractResourceTest {
*/
@Test
public void testCitySearch() throws Exception {
Response r = locationService.searchLocations(new PageConfig(0, 10), new SearchContext(Language.GERMAN), "Stuttgart");
Response r = locationService.searchLocations(new PageConfig(0, 10), new SearchContext(Language.GERMAN), "Stuttgart", false);
AssertResponse.isStatus(r, Status.OK);
LocationHierarchyPage page = AssertResponse.hasBody(r, LocationHierarchyPage.class);
Assert.assertTrue("Search for Stuttgart should have results.", page.getTotal() > 0 && page.getElements().size() > 0);
@@ -145,7 +145,7 @@ public class LocationResourceTest extends AbstractResourceTest {
@Test
public void testCityByStatePaging() {
// bonn, troisdorf, essen, duisburg, bochum, zuelpich + nwr = 7 results (6 cities + nrw)
Response r = locationService.searchLocations(new PageConfig(0, 10), new SearchContext(Language.GERMAN), "Nordrhein-Westfalen");
Response r = locationService.searchLocations(new PageConfig(0, 10), new SearchContext(Language.GERMAN), "Nordrhein-Westfalen", false);
LocationHierarchyPage page = AssertResponse.hasBody(r, LocationHierarchyPage.class);
Assert.assertEquals("Should find 7 results for NRW.", 7, page.getElements().size());
Assert.assertEquals("Type of NRW should be state.", page.getElements().get(0).getType(), LocationType.STATE);
@@ -162,7 +162,7 @@ public class LocationResourceTest extends AbstractResourceTest {
*/
@Test
public void testCityByCountryPaging() {
Response r = locationService.searchLocations(new PageConfig(0, 10), new SearchContext(Language.GERMAN), "Deutschland");
Response r = locationService.searchLocations(new PageConfig(0, 10), new SearchContext(Language.GERMAN), "Deutschland", false);
LocationHierarchyPage page = AssertResponse.hasBody(r, LocationHierarchyPage.class);
Assert.assertEquals("Should find 10 results for DE.", 10, page.getElements().size());
Assert.assertEquals("Type of DE should be country.", page.getElements().get(0).getType(), LocationType.COUNTRY);
@@ -88,7 +88,7 @@ public class SettingsResourceTest extends AbstractResourceTest {
Response r1 = userSettings.getCurrentUserSettings();
AssertResponse.isStatus(r1, Status.OK);
Settings settings = AssertResponse.hasBody(r1, Settings.class);
Response r2 = anonymousLocations.searchLocations(new PageConfig(0, 1), new SearchContext(Language.GERMAN) , "Bonn");
Response r2 = anonymousLocations.searchLocations(new PageConfig(0, 1), new SearchContext(Language.GERMAN) , "Bonn", false);
AssertResponse.isStatus(r2, Status.OK);
LocationHierarchyPage page = AssertResponse.hasBody(r2, LocationHierarchyPage.class);
List<LocationHierarchy> locations = page.getElements();