Search in sources :

Example 6 with SearchResult

use of fi.otavanopisto.muikku.search.SearchResult in project muikku by otavanopisto.

the class ElasticSearchProvider method freeTextSearch.

@Override
public SearchResult freeTextSearch(String text, int start, int maxResults) {
    try {
        text = sanitizeSearchString(text);
        SearchResponse response = elasticClient.prepareSearch().setQuery(matchQuery("_all", text)).setFrom(start).setSize(maxResults).execute().actionGet();
        List<Map<String, Object>> searchResults = new ArrayList<Map<String, Object>>();
        SearchHits searchHits = response.getHits();
        long totalHitCount = searchHits.getTotalHits();
        SearchHit[] results = searchHits.getHits();
        for (SearchHit hit : results) {
            Map<String, Object> hitSource = hit.getSource();
            hitSource.put("indexType", hit.getType());
            searchResults.add(hitSource);
        }
        SearchResult result = new SearchResult(start, maxResults, searchResults, totalHitCount);
        return result;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "ElasticSearch query failed unexpectedly", e);
        return new SearchResult(0, 0, new ArrayList<Map<String, Object>>(), 0);
    }
}
Also used : SearchHit(org.elasticsearch.search.SearchHit) ArrayList(java.util.ArrayList) SearchResult(fi.otavanopisto.muikku.search.SearchResult) UnknownHostException(java.net.UnknownHostException) SearchResponse(org.elasticsearch.action.search.SearchResponse) SearchHits(org.elasticsearch.search.SearchHits) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with SearchResult

use of fi.otavanopisto.muikku.search.SearchResult in project muikku by otavanopisto.

the class ElasticSearchProvider method search.

@Override
public SearchResult search(String query, String[] fields, int start, int maxResults, Class<?>... types) {
    try {
        query = sanitizeSearchString(query);
        String[] typenames = new String[types.length];
        for (int i = 0; i < types.length; i++) {
            typenames[i] = types[i].getSimpleName();
        }
        SearchRequestBuilder requestBuilder = elasticClient.prepareSearch("muikku").setTypes(typenames).setFrom(start).setSize(maxResults);
        BoolQueryBuilder boolQuery = boolQuery();
        for (String field : fields) {
            boolQuery.should(prefixQuery(field, query));
        }
        SearchResponse response = requestBuilder.setQuery(boolQuery).execute().actionGet();
        List<Map<String, Object>> searchResults = new ArrayList<Map<String, Object>>();
        SearchHits searchHits = response.getHits();
        long totalHitCount = searchHits.getTotalHits();
        SearchHit[] results = searchHits.getHits();
        for (SearchHit hit : results) {
            Map<String, Object> hitSource = hit.getSource();
            hitSource.put("indexType", hit.getType());
            searchResults.add(hitSource);
        }
        SearchResult result = new SearchResult(start, maxResults, searchResults, totalHitCount);
        return result;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "ElasticSearch query failed unexpectedly", e);
        return new SearchResult(0, 0, new ArrayList<Map<String, Object>>(), 0);
    }
}
Also used : SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) SearchHit(org.elasticsearch.search.SearchHit) ArrayList(java.util.ArrayList) SearchResult(fi.otavanopisto.muikku.search.SearchResult) UnknownHostException(java.net.UnknownHostException) SearchResponse(org.elasticsearch.action.search.SearchResponse) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) SearchHits(org.elasticsearch.search.SearchHits) HashMap(java.util.HashMap) Map(java.util.Map)

Example 8 with SearchResult

use of fi.otavanopisto.muikku.search.SearchResult in project muikku by otavanopisto.

the class UserSeekerResultProvider method search.

@Override
public List<SeekerResult> search(String searchTerm) {
    if (!sessionController.isLoggedIn())
        return null;
    SearchProvider elasticSearchProvider = getProvider("elastic-search");
    if (elasticSearchProvider != null) {
        String[] fields = new String[] { "firstName", "lastName", "nickName" };
        SearchResult result = elasticSearchProvider.search(searchTerm, fields, 0, 10, User.class);
        return searchResultProcessor.process(result);
    }
    return null;
}
Also used : SearchProvider(fi.otavanopisto.muikku.search.SearchProvider) SearchResult(fi.otavanopisto.muikku.search.SearchResult)

Example 9 with SearchResult

use of fi.otavanopisto.muikku.search.SearchResult in project muikku by otavanopisto.

the class WorkspaceRESTService method listWorkspaces.

@GET
@Path("/workspaces/")
@RESTPermit(handling = Handling.INLINE)
public Response listWorkspaces(@QueryParam("userId") Long userEntityId, @QueryParam("userIdentifier") String userId, @QueryParam("includeInactiveWorkspaces") @DefaultValue("false") Boolean includeInactiveWorkspaces, @QueryParam("search") String searchString, @QueryParam("subjects") List<String> subjects, @QueryParam("educationTypes") List<String> educationTypeIds, @QueryParam("curriculums") List<String> curriculumIds, @QueryParam("minVisits") Long minVisits, @QueryParam("includeUnpublished") @DefaultValue("false") Boolean includeUnpublished, @QueryParam("orderBy") List<String> orderBy, @QueryParam("firstResult") @DefaultValue("0") Integer firstResult, @QueryParam("maxResults") @DefaultValue("50") Integer maxResults, @Context Request request) {
    List<fi.otavanopisto.muikku.plugins.workspace.rest.model.Workspace> workspaces = new ArrayList<>();
    boolean doMinVisitFilter = minVisits != null;
    UserEntity userEntity = userEntityId != null ? userEntityController.findUserEntityById(userEntityId) : null;
    List<WorkspaceEntity> workspaceEntities = null;
    String schoolDataSourceFilter = null;
    List<String> workspaceIdentifierFilters = null;
    SchoolDataIdentifier userIdentifier = SchoolDataIdentifier.fromId(userId);
    if (userIdentifier != null) {
        if (doMinVisitFilter && userEntity == null) {
            userEntity = userEntityController.findUserEntityByUserIdentifier(userIdentifier);
        }
    }
    if (includeInactiveWorkspaces && userIdentifier == null) {
        return Response.status(Status.BAD_REQUEST).entity("includeInactiveWorkspaces works only with userIdentifier parameter").build();
    }
    if (includeInactiveWorkspaces && doMinVisitFilter) {
        return Response.status(Status.BAD_REQUEST).entity("includeInactiveWorkspaces cannot be used with doMinVisitFilter").build();
    }
    if (doMinVisitFilter) {
        if (!sessionController.isLoggedIn()) {
            return Response.status(Status.UNAUTHORIZED).entity("You need to be logged in to filter by visit count").build();
        }
        UserEntity loggedUserEntity = sessionController.getLoggedUserEntity();
        workspaceEntities = workspaceVisitController.listEnrolledWorkspaceEntitiesByMinVisitsOrderByLastVisit(loggedUserEntity, minVisits);
    } else {
        if (userIdentifier != null) {
            if (includeInactiveWorkspaces) {
                workspaceEntities = workspaceUserEntityController.listWorkspaceEntitiesByUserIdentifier(userIdentifier);
            } else {
                workspaceEntities = workspaceUserEntityController.listActiveWorkspaceEntitiesByUserIdentifier(userIdentifier);
            }
        } else if (userEntity != null) {
            workspaceEntities = workspaceUserEntityController.listActiveWorkspaceEntitiesByUserEntity(userEntity);
        } else {
            if (!sessionController.hasEnvironmentPermission(MuikkuPermissions.LIST_ALL_WORKSPACES)) {
                return Response.status(Status.FORBIDDEN).build();
            }
            workspaceEntities = Boolean.TRUE.equals(includeUnpublished) ? workspaceController.listWorkspaceEntities() : workspaceController.listPublishedWorkspaceEntities();
        }
    }
    Iterator<SearchProvider> searchProviderIterator = searchProviders.iterator();
    if (searchProviderIterator.hasNext()) {
        SearchProvider searchProvider = searchProviderIterator.next();
        SearchResult searchResult = null;
        if (workspaceEntities != null) {
            workspaceIdentifierFilters = new ArrayList<>();
            for (WorkspaceEntity workspaceEntity : workspaceEntities) {
                if (schoolDataSourceFilter == null) {
                    schoolDataSourceFilter = workspaceEntity.getDataSource().getIdentifier();
                }
                workspaceIdentifierFilters.add(workspaceEntity.getIdentifier());
            }
        }
        List<Sort> sorts = null;
        if (orderBy != null && orderBy.contains("alphabet")) {
            sorts = new ArrayList<>();
            sorts.add(new Sort("name.untouched", Sort.Order.ASC));
        }
        List<SchoolDataIdentifier> educationTypes = null;
        if (educationTypeIds != null) {
            educationTypes = new ArrayList<>(educationTypeIds.size());
            for (String educationTypeId : educationTypeIds) {
                SchoolDataIdentifier educationTypeIdentifier = SchoolDataIdentifier.fromId(educationTypeId);
                if (educationTypeIdentifier != null) {
                    educationTypes.add(educationTypeIdentifier);
                } else {
                    return Response.status(Status.BAD_REQUEST).entity(String.format("Malformed education type identifier", educationTypeId)).build();
                }
            }
        }
        List<SchoolDataIdentifier> curriculums = null;
        if (curriculumIds != null) {
            curriculums = new ArrayList<>(curriculumIds.size());
            for (String curriculumId : curriculumIds) {
                SchoolDataIdentifier curriculumIdentifier = SchoolDataIdentifier.fromId(curriculumId);
                if (curriculumIdentifier != null) {
                    curriculums.add(curriculumIdentifier);
                } else {
                    return Response.status(Status.BAD_REQUEST).entity(String.format("Malformed curriculum identifier", curriculumId)).build();
                }
            }
        }
        searchResult = searchProvider.searchWorkspaces(schoolDataSourceFilter, subjects, workspaceIdentifierFilters, educationTypes, curriculums, searchString, null, null, includeUnpublished, firstResult, maxResults, sorts);
        List<Map<String, Object>> results = searchResult.getResults();
        for (Map<String, Object> result : results) {
            String searchId = (String) result.get("id");
            if (StringUtils.isNotBlank(searchId)) {
                String[] id = searchId.split("/", 2);
                if (id.length == 2) {
                    String dataSource = id[1];
                    String identifier = id[0];
                    WorkspaceEntity workspaceEntity = workspaceEntityController.findWorkspaceByDataSourceAndIdentifier(dataSource, identifier);
                    if (workspaceEntity != null) {
                        String name = (String) result.get("name");
                        String description = (String) result.get("description");
                        String nameExtension = (String) result.get("nameExtension");
                        String subjectIdentifier = (String) result.get("subjectIdentifier");
                        Object curriculumIdentifiersObject = result.get("curriculumIdentifiers");
                        Set<String> curriculumIdentifiers = new HashSet<String>();
                        if (curriculumIdentifiersObject instanceof Collection) {
                            Collection<?> curriculumIdentifierCollection = (Collection<?>) curriculumIdentifiersObject;
                            for (Object o : curriculumIdentifierCollection) {
                                if (o instanceof String)
                                    curriculumIdentifiers.add((String) o);
                                else
                                    logger.warning("curriculumIdentifier not of type String");
                            }
                        }
                        if (StringUtils.isNotBlank(name)) {
                            workspaces.add(createRestModel(workspaceEntity, name, nameExtension, description, curriculumIdentifiers, subjectIdentifier));
                        }
                    }
                }
            }
        }
    } else {
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }
    if (workspaces.isEmpty()) {
        return Response.noContent().build();
    }
    if (orderBy.contains("lastVisit")) {
        Collections.sort(workspaces, new Comparator<fi.otavanopisto.muikku.plugins.workspace.rest.model.Workspace>() {

            @Override
            public int compare(fi.otavanopisto.muikku.plugins.workspace.rest.model.Workspace workspace1, fi.otavanopisto.muikku.plugins.workspace.rest.model.Workspace workspace2) {
                if (workspace1.getLastVisit() == null || workspace2.getLastVisit() == null) {
                    return 0;
                }
                if (workspace1.getLastVisit().before(workspace2.getLastVisit())) {
                    return 1;
                }
                if (workspace1.getLastVisit().after(workspace2.getLastVisit())) {
                    return -1;
                }
                return 0;
            }
        });
    }
    return Response.ok(workspaces).build();
}
Also used : SchoolDataIdentifier(fi.otavanopisto.muikku.schooldata.SchoolDataIdentifier) UserSchoolDataIdentifier(fi.otavanopisto.muikku.model.users.UserSchoolDataIdentifier) ArrayList(java.util.ArrayList) Sort(fi.otavanopisto.muikku.search.SearchProvider.Sort) HashSet(java.util.HashSet) SearchProvider(fi.otavanopisto.muikku.search.SearchProvider) SearchResult(fi.otavanopisto.muikku.search.SearchResult) UserEntity(fi.otavanopisto.muikku.model.users.UserEntity) WorkspaceUserEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceUserEntity) WorkspaceEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceEntity) Collection(java.util.Collection) Map(java.util.Map) HashMap(java.util.HashMap) Workspace(fi.otavanopisto.muikku.schooldata.entity.Workspace) Path(javax.ws.rs.Path) RESTPermit(fi.otavanopisto.security.rest.RESTPermit) GET(javax.ws.rs.GET)

Example 10 with SearchResult

use of fi.otavanopisto.muikku.search.SearchResult in project muikku by otavanopisto.

the class ElasticSearchProvider method matchAllSearch.

@Override
public SearchResult matchAllSearch(int start, int maxResults, Class<?>... types) {
    try {
        String[] typenames = new String[types.length];
        for (int i = 0; i < types.length; i++) {
            typenames[i] = types[i].getSimpleName();
        }
        SearchRequestBuilder requestBuilder = elasticClient.prepareSearch("muikku").setQuery(matchAllQuery()).setTypes(typenames).setFrom(start).setSize(maxResults);
        SearchResponse response = requestBuilder.execute().actionGet();
        List<Map<String, Object>> searchResults = new ArrayList<Map<String, Object>>();
        SearchHits searchHits = response.getHits();
        long totalHitCount = searchHits.getTotalHits();
        SearchHit[] results = searchHits.getHits();
        for (SearchHit hit : results) {
            Map<String, Object> hitSource = hit.getSource();
            hitSource.put("indexType", hit.getType());
            searchResults.add(hitSource);
        }
        SearchResult result = new SearchResult(start, maxResults, searchResults, totalHitCount);
        return result;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "ElasticSearch query failed unexpectedly", e);
        return new SearchResult(0, 0, new ArrayList<Map<String, Object>>(), 0);
    }
}
Also used : SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) SearchHit(org.elasticsearch.search.SearchHit) ArrayList(java.util.ArrayList) SearchResult(fi.otavanopisto.muikku.search.SearchResult) UnknownHostException(java.net.UnknownHostException) SearchResponse(org.elasticsearch.action.search.SearchResponse) SearchHits(org.elasticsearch.search.SearchHits) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

SearchResult (fi.otavanopisto.muikku.search.SearchResult)21 ArrayList (java.util.ArrayList)17 HashMap (java.util.HashMap)17 Map (java.util.Map)16 SchoolDataIdentifier (fi.otavanopisto.muikku.schooldata.SchoolDataIdentifier)13 UserEntity (fi.otavanopisto.muikku.model.users.UserEntity)10 SearchProvider (fi.otavanopisto.muikku.search.SearchProvider)9 SearchResponse (org.elasticsearch.action.search.SearchResponse)8 SearchHit (org.elasticsearch.search.SearchHit)8 SearchHits (org.elasticsearch.search.SearchHits)8 WorkspaceEntity (fi.otavanopisto.muikku.model.workspace.WorkspaceEntity)7 GET (javax.ws.rs.GET)7 Path (javax.ws.rs.Path)7 WorkspaceUserEntity (fi.otavanopisto.muikku.model.workspace.WorkspaceUserEntity)6 UnknownHostException (java.net.UnknownHostException)6 Date (java.util.Date)6 SearchRequestBuilder (org.elasticsearch.action.search.SearchRequestBuilder)6 UserSchoolDataIdentifier (fi.otavanopisto.muikku.model.users.UserSchoolDataIdentifier)5 BoolQueryBuilder (org.elasticsearch.index.query.BoolQueryBuilder)5 User (fi.otavanopisto.muikku.schooldata.entity.User)4