Giter VIP home page Giter VIP logo

mongo-spring-search's Introduction

MIT License Maven Central codecov

Mongo Spring Search

Mongo Spring Search provides a query language to a MongoDB database.
Explore the docs

Report Bug · Request Feature

Mongo Spring Search

Content index

What is this?

Mongo Spring Search provides a simple query language to perform advanced searches for your collections in MongoDB.

You could create custom repository methods to perform your searches. You could also use Mongo Spring Search to searching, sorting, pagination and combining logical operators.

Getting Started

Installation

Maven

Include the dependency to your project inside your pom.xml file

<dependency>
  <groupId>io.github.ajclopez</groupId>
  <artifactId>mongo-spring-search</artifactId>
  <version>1.0.4</version>
</dependency>
Gradle

Add implementation to your project in your build.gradle file

implementation 'io.github.ajclopez:mongo-spring-search:1.0.4'

Usage

Converts query into a MongoDB query object.

MongoSpringSearch.mss(String query)

MongoSpringSearch.mss(String query, Optional<Configuration> configuration)
Arguments

query: query string part of the requested API URL.

configuration: object for advanced configuration (See below) [optional].

You can add custom methods to your repository:

@Repository
public interface YourRepository extends MongoRepository<YourDocument, String>, YourCustomRepository {
}

To expand the Spring MongoRepository repository methods you can do it in the following way:

public interface YourCustomRepository {
	public List<YourDocument> findAll(String query);
}

In this class you can use Mongo Spring Search:

public class YourCustomRepositoryImpl implements YourCustomRepository {

	private MongoTemplate mongoTemplate;
	
	@Autowired
	public YourCustomRepositoryImpl(MongoTemplate mongoTemplate) {
		this.mongoTemplate = mongoTemplate;
	}
	
	@Override
	public List<YourDocument> findAll(String query) {
		return mongoTemplate.find(MongoSpringSearch.mss(query), YourDocument.class);
	}
}

Use it in your controller:

@GetMapping
public ResponseEntity<List<YourResponse>> yourFunctionNameHere(HttpServletRequest request) {
	return ResponseEntity.ok().body(yourRepository.findAll(request.getQueryString()));
}
Example
Query query = MongoSpringSearch.mss("status=sent&date>2020-01-06T14:00:00.000Z&author.firstname=Jhon&skip=50&limit=100&sort=-date&fields=id,date");

Supported features

Filtering

Operator URI Example
$eq key=val type=public
$ne key!=val status!=SENT
$gt key>val price>5
$gte key>=val price>=9
$lt key<val date<2020-01-01T14:00:00.000Z
$lte key<=val priority<=-5
$in key=val1,val2 status=QUEUED,DEQUEUED
$nin key!=val1,val2 status!=QUEUED,DEQUEUED
$exists key email
$exists !key !email
$regex key=/value/<opts> email=/@gmail\.com$/
$regex key!=/value/<opts> phone!=/^58/

Pagination

Useful to limit the number of records returned.

  • Operator keys are skip and limit.
  • Use limit operator to limit the number of records returned.
  • Use skip operator to skip the specified number of records.
skip=20&limit=10

Sorting

Useful to sort returned records.

  • Operator key is sort.
  • It accepts a comma-separated list of fields.
  • Use - prefixes to sort in descending order.
  • Use + prefixes to sort in ascedending order.
sort=id,-date

Projection

Useful to limit fields to return in each records.

  • Operator key is fields.
  • It accepts a comma-separated list of fields.
fields=firstname,lastname,phone,email

Note:

  • The _id field (returned by default).

Advanced queries

For more advanced usage (and, or logic operations), pass query filter as string with the logical operations, for example:

filter=(country=Mexico OR country=Spain) and gender=female
What operations are possible?
  • Filtering operations.
  • The AND/and operator.
  • The OR/or operator.
  • Parenthesis can be used for grouping.

Available options

You can use advanced options:

Configuration(Map<String, CastType> casters, Integer defaultLimit, Integer maxLimit)
  • casters object to specify custom casters, key is the caster name, and value is a type (BOOLEAN, NUMBER, PATTERN, DATE, STRING).
  • defaultLimit which contains custom value to return records.
  • maxLimit which contains custom value to return a maximum of records.

Customize limit value

You can specify your own maximum or default limit value.

  • defaultLimit: custom value to return records.
  • maxLimit: custom value to return a maximum of records.
Configuration options = new Configuration(null, 10, 500);

MongoSpringSearch.mss("organizationId=123&skip=10&limit=1000", Optional.of(options));

Specify casting per param keys

You can specify how query parameter values are casted by passing an object.

  • casters: object which map keys to casters.
Map<String, CastType> casters = new HashMap<String, CastType>();
casters.put("key1", CastType.STRING);
casters.put("key2", CastType.NUMBER);
casters.put("key3", CastType.STRING);
casters.put("key4", CastType.BOOLEAN);
		
Configuration options = new Configuration(casters, null, null);
MongoSpringSearch.mss("key1=VALUE&key2=10&key3=20&key4=true", Optional.of(options));

Contributing

Should you like to provide any feedback, please open up an Issue, I appreciate feedback and comments. Any contributions you make are greatly appreciated.

  1. Fork the Project
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing-feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This software is released under the MIT license. See LICENSE for more information.

mongo-spring-search's People

Contributors

ajclopez avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

mongo-spring-search's Issues

Error when using Advanced queries with ":" in key

When parsing following query:
filter=(captures.core:frequency>1 AND captures.core:frequency<5)

This log appears:
line 1:1 no viable alternative at input 'captures.core:frequency'

The resulted mogog query is:
Mongo Query: {}

Regex pattern not working

Hi Antonio,

Thanks for your library. I tried it our and it's amazing. I found one issue. When I tried with the regex pattern it's not working.

phone=/^58/. When I tried with the regex like this it didn't give me the results. It's giving empty list rather providing the phone numbers starting from 58. I tried to debug and find the issue. But no luck. Could you please help me to resolved this issue.

Thanks !

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.