Class: Contentstack::Query

Inherits:
Object
  • Object
show all
Defined in:
lib/contentstack/query.rb

Overview

A class that defines a query that is used to query for Entry instance.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(content_type) ⇒ Contentstack::Query

Initialize the Query instance Example:

@query   = @stack.content_type('blog').query
@entries = @query.where('author', 'John Doe').fetch

Parameters:

  • content_type (String)


24
25
26
27
28
29
30
31
32
33
# File 'lib/contentstack/query.rb', line 24

def initialize(content_type)
  @content_type = content_type
  @query = {
    query: "{}",
    include_count: false,
    skip: 0,
    count: 10,
    desc: 'created_at'
  }
end

Instance Attribute Details

#content_typeObject (readonly)

Returns the value of attribute content_type.



14
# File 'lib/contentstack/query.rb', line 14

attr_reader :query, :content_type

#queryObject (readonly)

Returns the value of attribute query.



# File 'lib/contentstack/query.rb', line 8

Instance Method Details

#add_query(field_uid, value) ⇒ Contentstack::Query

Add a custom query against specified key. Example:

@query   = @stack.content_type('blog').query
@query.add_query('author', "Jane Doe")

Parameters:

  • field_uid (String)
  • value (String/Number/Boolean/Hash)

Returns:



44
45
46
# File 'lib/contentstack/query.rb', line 44

def add_query(field_uid, value)
  add_query_hash({:"#{field_uid}" => value})
end

#and(queries) ⇒ Contentstack::Query

Combines all the queries together using AND operator.

Each query should be an instance of the Contentstack::Query class, and belong to the same `content_type` Example:

@query1 = @stack.content_type('category').query
@query1.where('title', 'Electronics')

@query2 = @stack.content_type('category').query
@query2.regex('description', '.*Electronics.*')

query_array = [@query1, @query2]

@query = @stack.content_type('category').query
@query.and(query_array)

Parameters:

  • queries (Array)

    Array of instances of the Query class

Returns:



140
141
142
143
# File 'lib/contentstack/query.rb', line 140

def and(queries)
  add_query_hash({"$and" => concat_queries(queries)})
  self
end

#ascending(field_uid) ⇒ Contentstack::Query

Sort the results in ascending order with the given key. Sort the returned entries in ascending order of the provided key.

Example

@query = @stack.content_type('category').query
@query.ascending

Parameters:

  • field_uid (String)

    The key to order by

Returns:



361
362
363
364
365
# File 'lib/contentstack/query.rb', line 361

def ascending(field_uid)
  @query.delete(:desc)
  @query[:asc] = field_uid
  self
end

#contained_in(field_uid, values) ⇒ Contentstack::Query Also known as: in

Add a constraint to the query that requires a particular key's entry to be contained in the provided array.

Example 1 - Array Equals Operator Within Group

@query = @stack.content_type('category').query
@query.contained_in("title", ["Electronics", "Apparel"])

Example 2 - Array Equals Operator Within Modular Blocks

@query = @stack.content_type('category').query
@query.contained_in("additional_info.deals.deal_name", ["Christmas Deal", "Summer Deal"])

Parameters:

  • field_uid (String)

    UID of the field for which query should be executed

  • values (String)

    The possible values for the key's object

Returns:



261
262
263
264
# File 'lib/contentstack/query.rb', line 261

def contained_in(field_uid, values)
  add_query_hash({:"#{field_uid}" => {"$in" => values}})
  self
end

#countInteger

Retrieve only count of entries in result.

Example

@query = @stack.content_type('category').query
@query.count

Returns:

  • (Integer)


334
335
336
337
# File 'lib/contentstack/query.rb', line 334

def count
  include_count
  fetch.count
end

#descending(field_uid) ⇒ Contentstack::Query

Sort the results in descending order with the given key. Sort the returned entries in descending order of the provided key.

Example

@query = @stack.content_type('category').query
@query.descending

Parameters:

  • field_uid (String)

    The key to order by

Returns:



377
378
379
380
381
# File 'lib/contentstack/query.rb', line 377

def descending(field_uid)
  @query.delete(:asc)
  @query[:desc] = field_uid
  self
end

#except(fields, fields_with_base = nil) ⇒ Contentstack::Query

Specifies list of field uids that would be 'excluded' from the response.

Example

# Exclude 'description' field in response
@query = @stack.content_type('category').query
@query.except(['description'])

# Query product and exclude the 'description' from category reference
@query = @stack.content_type('product').query
@query.include_reference('category')
      .except('category', ['description'])

Parameters:

  • fields (Array)

    Array of field uid which get 'excluded' from the response.

  • fields_with_base (Array) (defaults to: nil)

    Can be used to denote 'except' fields of the reference class

Returns:



444
445
446
447
448
449
450
451
452
453
454
455
456
# File 'lib/contentstack/query.rb', line 444

def except(fields, fields_with_base=nil)
  q = {}
  if [Array, String].include?(fields_with_base.class)
    fields_with_base = [fields_with_base] if fields_with_base.class == String
    q[fields.to_sym] = fields_with_base
  else
    fields = [fields] if fields.class == String
    q = {BASE: fields}
  end

  @query[:except] = q
  self
end

#exists?(field_uid) ⇒ Contentstack::Query

Add a constraint that requires, a specified key exists in response. Example:

@query = @stack.content_type('product').query
@query.exists?('product_image') # only fetch products which have a `product_image`

Parameters:

  • field_uid (String)

    The key to be constrained.

Returns:



105
106
107
# File 'lib/contentstack/query.rb', line 105

def exists?(field_uid)
  add_query_hash({:"#{field_uid}" => {"$exists" => true}})
end

#fetchContentstack::EntryCollection Also known as: find

Execute query

Example

@query = @stack.content_type('product').query
@query.tags(["tag1", "tag2"])
      .fetch


604
605
606
607
# File 'lib/contentstack/query.rb', line 604

def fetch
  entries = API.fetch_entries(@content_type, @query)
  EntryCollection.new(entries, @content_type)
end

#find_oneContentstack::Entry

Execute a Query and get the single matching object

Example

@query = @stack.content_type('product').query
@query.tags(["tag1", "tag2"])
      .find_one

Returns:



618
619
620
621
# File 'lib/contentstack/query.rb', line 618

def find_one
  limit 1
  fetch.first
end

#greater_than(field_uid, value) ⇒ Contentstack::Query

Add a constraint to the query that requires a particular key entry to be greater than the provided value.

Example

@query = @stack.content_type('product').query
@query.greater_than('price', '100')

Parameters:

  • field_uid (String)

    UID of the field for which query should be executed

  • value (String/Number)

    Value that provides a lower bound

Returns:



211
212
213
214
# File 'lib/contentstack/query.rb', line 211

def greater_than(field_uid, value)
  add_query_hash({:"#{field_uid}" => {"$gt" => value}})
  self
end

#greater_than_or_equal(field_uid, value) ⇒ Contentstack::Query

Add a constraint to the query that requires a particular key entry to be greater than or equal to the provided value.

Example

@query = @stack.content_type('product').query
@query.greater_than_or_equal('price', '100')

Parameters:

  • field_uid (String)

    UID of the field for which query should be executed

  • value (String/Number)

    Value that provides a lower bound

Returns:



227
228
229
230
# File 'lib/contentstack/query.rb', line 227

def greater_than_or_equal(field_uid, value)
  add_query_hash({:"#{field_uid}" => {"$gte" => value}})
  self
end

#include(field_uids) ⇒ Contentstack::Query

Returns:



572
573
574
575
576
577
# File 'lib/contentstack/query.rb', line 572

def include(field_uids)
  field_uids = [field_uids] if field_uids.class == String
  @query[:include] ||= []
  @query[:include] = @query[:include] | field_uids
  self
end

#include_branch(flag = true) ⇒ Contentstack::Entry

Include the branch for publish content.

Example

@query = @stack.content_type('product').query
@query.include_branch

Returns:



538
539
540
541
# File 'lib/contentstack/query.rb', line 538

def include_branch(flag=true)
  @query[:include_branch] = flag
  self
end

#include_content_type(flag = true) ⇒ Contentstack::Query

Include object's content_type in response

Example

@query = @stack.content_type('product').query
@query.include_content_type

Returns:



511
512
513
514
# File 'lib/contentstack/query.rb', line 511

def include_content_type(flag=true)
  @query[:include_content_type] = flag
  self
end

#include_count(flag = true) ⇒ Contentstack::Query

Retrieve count and data of objects in result.

Example

@query = @stack.content_type('category').query
@query.include_count

Returns:



346
347
348
349
# File 'lib/contentstack/query.rb', line 346

def include_count(flag=true)
  @query[:include_count] = flag
  self
end

#include_draft(flag = true) ⇒ Contentstack::Query

Include objects in 'Draft' mode in response

Example

@query = @stack.content_type('product').query
@query.include_draft

Returns:



564
565
566
567
# File 'lib/contentstack/query.rb', line 564

def include_draft(flag=true)
  @query[:include_draft] = flag
  self
end

#include_embedded_itemsContentstack::Query

Include Embedded Objects (Entries and Assets) along with entry/entries details.

Example

@query = @stack.content_type('product').query
@query.include_embedded_items

Returns:



551
552
553
554
# File 'lib/contentstack/query.rb', line 551

def include_embedded_items()
  @query[:include_embedded_items] = ['BASE']
  self
end

#include_fallback(flag = true) ⇒ Contentstack::Query

Include the fallback locale publish content, if specified locale content is not publish.

Example

@query = @stack.content_type('product').query
@query.include_fallback

Returns:



525
526
527
528
# File 'lib/contentstack/query.rb', line 525

def include_fallback(flag=true)
  @query[:include_fallback] = flag
  self
end

#include_owner(flag = true) ⇒ Contentstack::Query

Include object owner's profile in the objects data.

Example

@query = @stack.content_type('product').query
@query.include_owner

Returns:



498
499
500
501
# File 'lib/contentstack/query.rb', line 498

def include_owner(flag=true)
  @query[:include_owner] = flag
  self
end

#include_reference(reference_field_uids) ⇒ Contentstack::Query

Add a constraint that requires a particular reference key details.

Example

# Include reference of 'category'
@query = @stack.content_type('product').query
@query.include_reference('category')

# Include reference of 'category' and 'reviews'
@query = @stack.content_type('product').query
@query.include_reference(['category', 'reviews'])

Parameters:

  • reference_field_uids (String/Array)

    Pass string or array of reference fields that must be included in the response

Returns:



473
474
475
# File 'lib/contentstack/query.rb', line 473

def include_reference(reference_field_uids)
  self.include(reference_field_uids)
end

#include_schema(flag = true) ⇒ Contentstack::Query

Include schemas of all returned objects along with objects themselves.

Example

@query = @stack.content_type('product').query
@query.include_schema

Returns:



485
486
487
488
# File 'lib/contentstack/query.rb', line 485

def include_schema(flag=true)
  @query[:include_schema] = flag
  self
end

#less_than(field_uid, value) ⇒ Contentstack::Query

Add a constraint to the query that requires a particular key entry to be less than the provided value.

Example

@query = @stack.content_type('product').query
@query.less_than('price', '100')

Parameters:

  • field_uid (String)

    UID of the field for which query should be executed

  • value (String/Number)

    Value that provides an upper bound

Returns:



179
180
181
182
# File 'lib/contentstack/query.rb', line 179

def less_than(field_uid, value)
  add_query_hash({:"#{field_uid}" => {"$lt" => value}})
  self
end

#less_than_or_equal(field_uid, value) ⇒ Contentstack::Query

Add a constraint to the query that requires a particular key entry to be less than or equal to the provided value.

Example

@query = @stack.content_type('product').query
@query.less_than_or_equal('price', '100')

Parameters:

  • field_uid (String)

    UID of the field for which query should be executed

  • value (String/Number)

    Value that provides an upper bound

Returns:



195
196
197
198
# File 'lib/contentstack/query.rb', line 195

def less_than_or_equal(field_uid, value)
  add_query_hash({:"#{field_uid}" => {"$lte" => value}})
  self
end

#limit(count = 10) ⇒ Contentstack::Query

A limit on the number of objects to return.

Example

@query = @stack.content_type('category').query
@query.limit(50)

Parameters:

  • count (Number) (defaults to: 10)

    of objects to limit in resulset.

Returns:



322
323
324
325
# File 'lib/contentstack/query.rb', line 322

def limit(count=10)
  @query[:limit] = count
  self
end

#locale(code) ⇒ Contentstack::Query

Get entries from the specified locale.

Example

Change language method
@query = @stack.content_type('category').query
@query.locale('en-us')

Parameters:

  • code (String)

    The locale code of the entry

Returns:



393
394
395
396
# File 'lib/contentstack/query.rb', line 393

def locale(code)
  @query[:locale] = code
  self
end

#not_contained_in(field_uid, values) ⇒ Contentstack::Query Also known as: not_in

Add a constraint to the query that requires a particular key entry's value not be contained in the provided array.

Example 1 - Array Not-equals Operator Within Group

@query = @stack.content_type('category').query
@query.not_contained_in("title", ["Electronics", "Apparel"])

Example 2 - Array Not-equals Operator Within Modular Blocks

@query = @stack.content_type('category').query
@query.not_contained_in("additional_info.deals.deal_name", ["Christmas Deal", "Summer Deal"])

Parameters:

  • field_uid (String)

    UID of the field for which query should be executed

  • values (String)

    The possible values for the key's object

Returns:



280
281
282
283
# File 'lib/contentstack/query.rb', line 280

def not_contained_in(field_uid, values)
  add_query_hash({:"#{field_uid}" => {"$nin" => values}})
  self
end

#not_equal_to(field_uid, value) ⇒ Contentstack::Query

Add a constraint to the query that requires a particular key's entry to be not equal to the provided value.

Example

@query = @stack.content_type('product').query
@query.not_equal_to('price', '100')

Parameters:

  • field_uid (String)

    UID of the field for which query should be executed

  • value (String)

    The object that must not be equaled.

Returns:



242
243
244
245
# File 'lib/contentstack/query.rb', line 242

def not_equal_to(field_uid, value)
  add_query_hash({:"#{field_uid}" => {"$ne" => value}})
  self
end

#not_exists?(field_uid) ⇒ Contentstack::Query

Add a constraint that requires, a specified key does not exists in response. Example:

@query = @stack.content_type('product').query
@query.not_exists?('product_image') # only fetch products which do not have a `product_image`

Parameters:

  • field_uid (String)

    The key to be constrained.

Returns:



117
118
119
120
# File 'lib/contentstack/query.rb', line 117

def not_exists?(field_uid)
  add_query_hash({:"#{field_uid}" => {"$exists" => false}})
  self
end

#only(fields, fields_with_base = nil) ⇒ Contentstack::Query

Specifies an array of 'only' keys in BASE object that would be 'included' in the response.

Example

# Include only title and description field in response
@query = @stack.content_type('category').query
@query.only(['title', 'description'])

# Query product and include only the title and description from category reference
@query = @stack.content_type('product').query
@query.include_reference('category')
      .only('category', ['title', 'description'])

Parameters:

  • fields (Array)

    Array of the 'only' reference keys to be included in response.

  • fields_with_base (Array) (defaults to: nil)

    Can be used to denote 'only' fields of the reference class

Returns:



414
415
416
417
418
419
420
421
422
423
424
425
426
# File 'lib/contentstack/query.rb', line 414

def only(fields, fields_with_base=nil)
  q = {}
  if [Array, String].include?(fields_with_base.class)
    fields_with_base = [fields_with_base] if fields_with_base.class == String
    q[fields.to_sym] = fields_with_base
  else
    fields = [fields] if fields.class == String
    q = {BASE: fields}
  end

  @query[:only] = q
  self
end

#or(queries) ⇒ Contentstack::Query

Combines all the queries together using OR operator.

Each query should be an instance of the Contentstack::Query class, and belong to the same `content_type` Example:

@query1 = @stack.content_type('category').query
@query1.where('title', 'Electronics')

@query2 = @stack.content_type('category').query
@query2.where('title', 'Apparel')

query_array = [@query1, @query2]

@query = @stack.content_type('category').query
@query.or(query_array)

Parameters:

  • queries (Array)

    Array of instances of the Query class

Returns:



163
164
165
166
# File 'lib/contentstack/query.rb', line 163

def or(queries)
  add_query_hash({"$or" => concat_queries(queries)})
  self
end

#regex(field_uid, pattern, options = "") ⇒ Contentstack::Query

Add a regular expression constraint for finding string values that match the provided regular expression. This may be slow for large data sets. Example:

@query = @stack.content_type('product').query
@query.regex('title', '.*Mobile.*', 'i') # Search without case sensitivity

Parameters:

  • field_uid (String)

    The key to be constrained.

  • pattern (String)

    The regular expression pattern to match.

  • options (String) (defaults to: "")

    Regex options

Returns:



85
86
87
88
89
90
91
92
93
94
95
# File 'lib/contentstack/query.rb', line 85

def regex(field_uid, pattern, options="")
  hash = {
    "#{field_uid}" => {
      "$regex": pattern
    }
  }

  hash["#{field_uid}"]["$options"] = options if !options.empty? || !options.nil?

  add_query_hash(hash)
end

#remove_query(field_uid) ⇒ Contentstack::Query

Remove provided query key from custom query if exist. Example:

@query   = @stack.content_type('blog').query
@query.remove_query('author')

Parameters:

  • field_uid (String)

Returns:



56
57
58
59
60
61
# File 'lib/contentstack/query.rb', line 56

def remove_query(field_uid)
  q = ActiveSupport::JSON.decode(@query[:query])
  q.delete(field_uid)
  @query[:query] = ActiveSupport::JSON.encode(q)
  self
end

#search(text) ⇒ Contentstack::Query

Deprecated.

since version 0.5.0

This method provides only the entries matching the specified value. Example

@query = @stack.content_type('product').query
@query.search("This is an awesome product")

Parameters:

  • text (String)

    value used to match or compare

Returns:



308
309
310
311
# File 'lib/contentstack/query.rb', line 308

def search(text)
  @query[:typeahead] = text
  self
end

#skip(count) ⇒ Contentstack::Query

The number of objects to skip before returning any.

Example

@query = @stack.content_type('category').query
@query.skip(50)

Parameters:

  • count (Number)

    of objects to skip from resulset.

Returns:



294
295
296
297
# File 'lib/contentstack/query.rb', line 294

def skip(count)
  @query[:skip] = count
  self
end

#tags(tags_array) ⇒ Contentstack::Query

Include tags with which to search entries.

Example

@query = @stack.content_type('product').query
@query.tags(["tag1", "tag2"])

Parameters:

  • tags_array (Array)

    Array of tags using which search must be performed

Returns:



589
590
591
592
# File 'lib/contentstack/query.rb', line 589

def tags(tags_array)
  @query[:tags] = tags_array
  self
end

#where(query_hash) ⇒ Contentstack::Query

Add a constraint to fetch all entries that contains given value against specified key. Example:

@query = @stack.content_type('blog').query
@query.where({:author => "Jane Doe"})

Parameters:

  • query_hash (Hash)

Returns:



71
72
73
# File 'lib/contentstack/query.rb', line 71

def where(query_hash)
  add_query_hash(query_hash)
end