3

I'm trying to do something through the Contentful API (npm module of the content delivery) and I'm not sure if it's possible.

I have a content type tag in Contentful which has 1 field, also called tag. I then have another content type called article which has a multiple reference field called tags. This field allows an editor to link multiple tag entries to the article.

Now when the user loads the article, I want to display similar reading by using the tags to find other articles with the same tags.

So the relevant JSON structure of an article looks something like this:

{
  sys: {...},
  fields: {
    tags: [
      {
        sys: {...},
        fields: { tag: "Football" }
      },
      {
        sys: {...},
        fields: { tag: "Leeds United" }
      },
      {
        sys: {...},
        fields: { tag: "Elland Road" }
      }
    ]
  }
}

So say the article the user is reading has the tags football, Leeds United and Elland Road. How would I use the API to return other articles with those 3 tags, or some of those tags. For example and article with all 3 tags would be a strong match, but an article with just 1 matching tag would be weak.

I tried using the inclusion rule like so:

contentClient.entries({
  "content_type": "xxxxxxxx",
  "fields.tags[in]": ["football", "Leeds United"],
}, function(err, entries){
  if (err) throw err;
  console.log(entries);
});

This of course doesn't work because the field with the value in is not fields.tags[in] it's fields.tags.fields.tag.

CaribouCode
  • 13,998
  • 28
  • 102
  • 174

2 Answers2

3

You can achieve an inclusion query by determining the sys.id of your tags and then doing a query for them, by changing your dictionary to this:

{
  "content_type": "xxxxxxxx",
  "fields.tags.sys.id[in]": "tagId1, tagId2",
}

The content delivery module doesn't marshall arrays, so the argument needs to be a comma-separated string. The Content Delivery API doesn't support scoring, so using that query you would just get a list of all entries which have a link to one or more of those tags, but it will not be sorted by strong/weak matches in any way.

Seth
  • 10,198
  • 10
  • 45
  • 68
NeoNacho
  • 680
  • 1
  • 5
  • 13
  • Thank you!!!! I've been trying to do this for 2 days. Their documentation is wrong! https://github.com/contentful/contentful.js They tell you to use an array there. – CaribouCode Sep 23 '15 at 15:43
  • Can you specify an equivalent http request for this @NeoNacho – Aswin Raghavan Oct 16 '15 at 06:02
  • This was perfect! Thank you so much! I keep forgetting that every entry you make is tied to their respective `sys.id`. – Sam Sverko Sep 03 '20 at 19:20
2
client.getEntries({
  content_type: '<content_type_id>',
  'fields.<field_name>[in]': 'accessories,flowers'
})

It is as per documentation and pay attention that there is no space after comma between 'accessories,flowers'

Seth
  • 10,198
  • 10
  • 45
  • 68